Reputation: 1491
I have a string that contains many underscores followed by words ex: "Field_4_txtbox
" I need to find the last underscore in the string and remove everything following it(including the "_"), so it would return to me "Field_4
" but I need this to work for different length ending strings. So I can't just trim a fixed length.
I know I can do an If statement that checks for certain endings like
if(strstr($key,'chkbox')) {
$string= rtrim($key, '_chkbox');
}
but I would like to do this in one go with a regex pattern, how can I accomplish this?
Upvotes: 5
Views: 4216
Reputation: 65264
There is no need to use an extremly costly regex, a simple strrpos()
would do the job:
$string=substr($key,0,strrpos($key,"_"));
strrpos — Find the position of the last occurrence of a substring in a string
Upvotes: 6
Reputation: 14921
You can also just use explode()
:
$string = 'Field_4_txtbox';
$temp = explode('_', strrev($string), 2);
$string = strrev($temp[1]);
echo $string;
As of PHP 5.4+
$string = 'Field_4_txtbox';
$string = strrev(explode('_', strrev($string), 2)[1]);
echo $string;
Upvotes: 2
Reputation: 58224
The matching regex would be:
/_[^_]*$/
Just replace that with '':
preg_replace( '/_[^_]*$/', '', your_string );
Upvotes: 11