Undermine2k
Undermine2k

Reputation: 1491

how to remove last occurance of underscore in string

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

Answers (3)

Eugen Rieck
Eugen Rieck

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

HamZa
HamZa

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

lurker
lurker

Reputation: 58224

The matching regex would be:

/_[^_]*$/

Just replace that with '':

preg_replace( '/_[^_]*$/', '', your_string );

Upvotes: 11

Related Questions