PHP substring extraction. Get the string before the first '/' or the whole string

anon355079 picture anon355079 · Dec 20, 2009 · Viewed 288.8k times · Source

I am trying to extract a substring. I need some help with doing it in PHP.

Here are some sample strings I am working with and the results I need:

home/cat1/subcat2 => home

test/cat2 => test

startpage => startpage

I want to get the string till the first /, but if no / is present, get the whole string.

I tried,

substr($mystring, 0, strpos($mystring, '/'))

I think it says - get the position of / and then get the substring from position 0 to that position.

I don't know how to handle the case where there is no /, without making the statement too big.

Is there a way to handle that case also without making the PHP statement too complex?

Answer

jmarceli picture jmarceli · Jun 18, 2014

The most efficient solution is the strtok function:

strtok($mystring, '/')

NOTE: In case of more than one character to split with the results may not meet your expectations e.g. strtok("somethingtosplit", "to") returns s because it is splitting by any single character from the second argument (in this case o is used).

@friek108 thanks for pointing that out in your comment.

For example:

$mystring = 'home/cat1/subcat2/';
$first = strtok($mystring, '/');
echo $first; // home

and

$mystring = 'home';
$first = strtok($mystring, '/');
echo $first; // home