Get first string before separator?
Asked Answered
M

3

7

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!

Meyer answered 10/1, 2012 at 9:40 Comment(0)
M
9
$str = '7_string_12';
echo substr($str,0,strrpos($str,'_'));

echoes

7_string

no matter what's at the begining of the string

Mcchesney answered 10/1, 2012 at 9:44 Comment(3)
Thanks ! I've another question! How to make this code to show me the following result : string ? That is to show string between separators. Thanks in advance !Meyer
@dilyan_kn preg_match('/_(\S+)_/',$str,$m); echo $m[1];Mcchesney
Please note, substr($str,0,strrpos($str,'_')) is OK if the input isn't like 7_string2_abc_123. Because the output will be 7_string2_abc.Pushing
E
1

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().

Edgerton answered 10/1, 2012 at 9:45 Comment(0)
J
1
$s1 = '7_string_12';
echo substr($s1, 0, strpos($s1, '_', 2));
Jugurtha answered 10/1, 2012 at 9:46 Comment(1)
The assumption that the first token is always one character long is a bit dangerous.Haydeehayden

© 2022 - 2024 — McMap. All rights reserved.