Get the first line before the delimiter?

I have lines with the following structure:

7_string_12 7_string2_122 7_string3_1223 

How can I get the line before the second "_"?

I want my end result to be:

 7_string 7_string2 7_string3 

I use explode ('_', $ string) and concatenate the first two values, but my script was very slow!

+6
source share
3 answers
 $str = '7_string_12'; echo substr($str,0,strrpos($str,'_')); 

echoes

 7_string 

no matter what at the beginning of the line

+8
source
 $s1 = '7_string_12'; echo substr($s1, 0, strpos($s1, '_', 2)); 
+1
source

If it always starts with 7_, you can try the following:

 $string = substr($text, 0, strpos($text, '_', 2)); 

strpos () searches for the first _, starting with character 3 (= s from the string). Then you use substr () to select the whole line, starting from the first character, to the character returned by strpos ().

0
source

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


All Articles