200

I've got a string and I'd like to get everything after a certain value. The string always starts off with a set of numbers and then an underscore. I'd like to get the rest of the string after the underscore. So for example if I have the following strings and what I'd like returned:

"123_String" -> "String"
"233718_This_is_a_string" -> "This_is_a_string"
"83_Another Example" -> "Another Example"

How can I go about doing something like this?

Spencer O'Reilly
  • 515
  • 1
  • 7
  • 20
user1048676
  • 9,756
  • 26
  • 83
  • 120

9 Answers9

441

The strpos() finds the offset of the underscore, then substr grabs everything from that index plus 1, onwards.

$data = "123_String";    
$whatIWant = substr($data, strpos($data, "_") + 1);    
echo $whatIWant;

If you also want to check if the underscore character (_) exists in your string before trying to get it, you can use the following:

if (($pos = strpos($data, "_")) !== FALSE) { 
    $whatIWant = substr($data, $pos+1); 
}
kenorb
  • 155,785
  • 88
  • 678
  • 743
databyss
  • 6,318
  • 1
  • 20
  • 24
  • 2
    What would be the best what to check if the underscore exists, e.g its optional. – John Magnolia Feb 18 '13 at 02:46
  • 3
    @JohnMagnolia: Then you can just use `if (($pos = strpos($data, "_")) !== FALSE) { $whatIWant = substr($data, $pos+1); }` – Amal Murali Apr 09 '14 at 11:03
  • 11
    @JohnMagnolia Or a little fancy one-liner: `substr($data, (strrpos($data, '_') ?: -1) +1)`. – flu Jan 07 '15 at 13:49
  • 4
    @flu I think you meant to say, harder to read. IMO, less lines does not mean fancier. – M H Jan 12 '17 at 16:01
  • This function will return string after some substring/char or false if needle is not found: `function StrAfterStr($S, $H) { return (($P = strpos($S, $H)) !== false) ? substr($S, $P + 1) : false; }` – Marcodor Mar 02 '17 at 14:05
  • How would i modify this code to say fetch from a certain position 'n' upto an specific character '-'. For example: the string is "A: hello B: world | bye ;" how can i fetch the keyword 'world' (or any other sentence in that place ) knowing that it will always occur between 'B:' & '|' ? Any help is much appreciated. – FreeKrishna May 18 '17 at 05:37
  • This will handle your specific case (http://codepad.org/4mB9YhvM) The gist is that you find the position of your starting marker, then find the position of the ending marker (checking after your starting marker), then just grab the characters between that. – databyss May 19 '17 at 16:36
  • If you need to get string after *last* occurence of the symbol, you can use `strrpos` – The Godfather Aug 13 '18 at 15:55
  • If data comes from outside and is, for example, a numeric string, result is strange: `substr('456', strpos('456', "_") + 1)` gives `56`. – Boolean_Type Jun 14 '22 at 19:06
36

strtok is an overlooked function for this sort of thing. It is meant to be quite fast.

$s = '233718_This_is_a_string';
$firstPart = strtok( $s, '_' );
$allTheRest = strtok( '' ); 

Empty string like this will force the rest of the string to be returned.

NB if there was nothing at all after the '_' you would get a FALSE value for $allTheRest which, as stated in the documentation, must be tested with ===, to distinguish from other falsy values.

mike rodent
  • 14,126
  • 11
  • 103
  • 157
  • 3
    Be careful: strtok will return the portion of the string *after* the character if it is the first character in the string, e.g., `strtok('a_b', '_')` will return `a` but `strtok('_b', '_')` will return `b`, not an empty string as you'd expect – Quinn Comendant May 25 '19 at 03:08
  • Hmm re this comment, I think I wouldn't "expect" an empty string, I would probably *wonder whether* I was going to get an empty string... – mike rodent Feb 19 '21 at 16:13
  • 1
    My comment was an attempt to say that this answer will break if `_` is the first character. If `$s` in the code above is `"_This_is_a_string"` the result will be `is_a_string`, not `This_is_a_string`. Therefore, it is not a solution to _“How to get everything after a certain character?”_ for every case. – Quinn Comendant Feb 20 '21 at 22:32
  • I had no idea this function existed. – Andrew Fox May 25 '23 at 23:56
18

Here is the method by using explode:

$text = explode('_', '233718_This_is_a_string', 2)[1]; // Returns This_is_a_string

or:

$text = end((explode('_', '233718_This_is_a_string', 2)));

By specifying 2 for the limit parameter in explode(), it returns array with 2 maximum elements separated by the string delimiter. Returning 2nd element ([1]), will give the rest of string.


Here is another one-liner by using strpos (as suggested by @flu):

$needle = '233718_This_is_a_string';
$text = substr($needle, (strpos($needle, '_') ?: -1) + 1); // Returns This_is_a_string
Wadih M.
  • 12,810
  • 7
  • 47
  • 57
kenorb
  • 155,785
  • 88
  • 678
  • 743
  • 1
    The silencer `@` is a bad coding practice. The error gets silenced, but the error keeps getting logged. Your disk will get full. – Binar Web Apr 16 '21 at 10:18
12

I use strrchr(). For instance to find the extension of a file I use this function:

$string = 'filename.jpg';
$extension = strrchr( $string, '.'); //returns "jpg"
Pinonirvana
  • 920
  • 1
  • 8
  • 12
5

Another simple way, using strchr() or strstr():

$str = '233718_This_is_a_string';

echo ltrim(strstr($str, '_'), '_'); // This_is_a_string

In your case maybe ltrim() alone will suffice:

echo ltrim($str, '0..9_'); // This_is_a_string

But only if the right part of the string (after _) does not start with numbers, otherwise it will also be trimmed.

nggit
  • 611
  • 8
  • 8
3

if anyone needs to extract the first part of the string then can try,

Query:

$s = "This_is_a_string_233718";

$text = $s."_".substr($s, 0, strrpos($s, "_"));

Output:

This_is_a_string

Keshav Pradeep Ramanath
  • 1,623
  • 4
  • 24
  • 33
Ady
  • 137
  • 1
  • 2
1
$string = "233718_This_is_a_string";
$withCharacter = strstr($string, '_'); // "_This_is_a_string"
echo substr($withCharacter, 1); // "This_is_a_string"

In a single statement it would be.

echo substr(strstr("233718_This_is_a_string", '_'), 1); // "This_is_a_string"
Ali A. Dhillon
  • 575
  • 7
  • 6
0

If you want to get everything after certain characters and if those characters are located at the beginning of the string, you can use an easier solution like this:

$value = substr( '123_String', strlen( '123_' ) );
echo $value; // String
arafatgazi
  • 341
  • 4
  • 5
0

Use this line to return the string after the symbol or return the original string if the character does not occur:

$newString = substr($string, (strrpos($string, '_') ?: -1) +1);
Gerard de Visser
  • 7,590
  • 9
  • 50
  • 58