Home » Php » php – Get first string before separator?

php – Get first string before separator?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have strings with folowing structure:

7_string_12
7_string2_122
7_string3_1223

How I can get string before second “_” ?

I want my final result to be :

7_string
7_string2
7_string3

I am using explode(‘_’, $string) and combine first two values, but my script was very slow!

How to&Answers:
$str = '7_string_12';
echo substr($str,0,strrpos($str,'_'));

echoes

7_string

no matter what’s at the begining of the string

Answer:

If it always starts with 7_ you can try this:

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

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

Answer:

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