How can I split a string at the first occurrence of - (minus sign) into two $vars with PHP?
I have found how to split on every "-" but, not only on the first occurrence.
example:
this - is - line - of whatever - is - relevant $var1 = this $var2 = is - line - of whatever - is - relevant
Note, also stripped the first "-" .
Thanks in advance for the help!
To split a JavaScript string only on the first occurrence of a character, call the slice() method on the string, passing it the index of the character + 1 as a parameter. The slice method will return the portion of the string after the first occurrence of the character.
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.
Use explode() or preg_split() function to split the string in php with given delimiter. PHP | explode() Function: The explode() function is an inbuilt function in PHP which is used to split a string in different strings.
Use the str. split() method with maxsplit set to 1 to split a string on the first occurrence, e.g. my_str. split('-', 1) .
It's very simple, using an extra paramater to explode
that many people don't realize is there:
list($before, $after) = explode('-', $source, 2);
$array = explode('-', 'some-string', 2);
Then you could do $var1=$array[0]
and $var2=$array[1]
.
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