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?
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.
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.
string = string. replace(/\/$/, "");
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.
The matching regex would be:
/_[^_]*$/
Just replace that with '':
preg_replace( '/_[^_]*$/', '', your_string );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With