How to remove the last underline value in a string

I have a line containing many underscores followed by ex: " Field_4_txtbox " I need to find the last underscore in the line and delete everything after it (including "_"), so it will return to me " Field_4 ", but I need this to work for strings with different lengths. So I can’t just crop a fixed length.

I know that I can execute the If statement, which checks for certain endings, such as

 if(strstr($key,'chkbox')) { $string= rtrim($key, '_chkbox'); } 

but I would like to do it at a time with a regex pattern, how can I do this?

+4
source share
3 answers

The corresponding regular expression will be:

 /_[^_]*$/ 

Just replace this with '':

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

There is no need to use an extremely expensive regular expression, a simple strrpos() will do the job:

 $string=substr($key,0,strrpos($key,"_")); 

strrpos . Find the position of the last occurrence of the substring in the line

+5
source

You can also just use explode() :

 $string = 'Field_4_txtbox'; $temp = explode('_', strrev($string), 2); $string = strrev($temp[1]); echo $string; 

Starting with PHP 5.4+

 $string = 'Field_4_txtbox'; $string = strrev(explode('_', strrev($string), 2)[1]); echo $string; 
+2
source

Source: https://habr.com/ru/post/1483241/


All Articles