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?
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.
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.
“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.
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); }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With