Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove last occurance of underscore in string

Tags:

regex

php

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?

like image 552
Undermine2k Avatar asked May 28 '13 23:05

Undermine2k


People also ask

How do I remove the last occurrence of a string underscore in Python?

Remove Character from String Python: replace() The replace() method removes the underscore character from the original string and replaces all instances of that character with an empty string.

How do you remove underscore from a string?

To remove the underscores from a string, call the replaceAll() method on the string, passing it an underscore as the first parameter, and an empty string as the second, e.g. replaceAll('_', '') . The replaceAll method will return a new string, where all underscores are removed.

How to remove last character from string using regex?

string = string. replace(/\/$/, "");

How do you remove the last occurring of a character in a string in python?

rstrip. The string method rstrip removes the characters from the right side of the string that is given to it. So, we can use it to remove the last element of the string. We don't have to write more than a line of code to remove the last char from the string.


1 Answers

The matching regex would be:

/_[^_]*$/

Just replace that with '':

preg_replace( '/_[^_]*$/', '', your_string );
like image 81
lurker Avatar answered Oct 05 '22 19:10

lurker