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!

BenMorel
  • 34,448
  • 50
  • 182
  • 322
dido
  • 2,330
  • 8
  • 37
  • 54

3 Answers3

9
$str = '7_string_12';
echo substr($str,0,strrpos($str,'_'));

echoes

7_string

no matter what's at the begining of the string

k102
  • 7,861
  • 7
  • 49
  • 69
  • 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 ! – dido Jan 11 '12 at 11:33
  • @dilyan_kn `preg_match('/_(\S+)_/',$str,$m); echo $m[1];` – k102 Jan 11 '12 at 11:38
  • 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`. – yasouser Jan 02 '14 at 18:28
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().

stefandoorn
  • 1,032
  • 8
  • 12
1
$s1 = '7_string_12';
echo substr($s1, 0, strpos($s1, '_', 2));
Alex Pliutau
  • 21,392
  • 27
  • 113
  • 143