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

The most efficient solution is the strtok function:

strtok($mystring, "https://stackoverflow.com/")

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, "https://stackoverflow.com/");
echo $first; // home

and

$mystring = 'home';
$first = strtok($mystring, "https://stackoverflow.com/");
echo $first; // home

Leave a Comment