Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get everything after a certain character?

Tags:

string

php

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?

like image 530
user1048676 Avatar asked Jul 10 '12 01:07

user1048676


People also ask

How do you get the string after a certain character?

To get the substring after a specific character, call the substring() method, passing it the index after the character's index as a parameter. The substring method will return the part of the string after the specified character. Copied! We used the String.

How split a string after a specific character in PHP?

explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.

How do you slice a string after?

“javascript slice string after character” Code Answer'svar string = "55+5"; // Just a variable for your input. character as a delimiter. Then it gets the first element of the split string.


2 Answers

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);  } 
like image 56
databyss Avatar answered Oct 02 '22 21:10

databyss


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.

like image 27
mike rodent Avatar answered Oct 02 '22 23:10

mike rodent