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

04/03/2020 14:30:01

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?

Verified Answer (250 Votes)

12/20/2009 19:11:03

Use explode()

$arr = explode("/", $string, 2);
$first = $arr[0];

In this case, I'm using the limit parameter to explode so that php won't scan the string any more than what's needed.


Answer #2 (278 Votes)

06/18/2014 13:03:57

The most efficient solution is the strtok function:

strtok($mystring, '/')

For example:

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


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

Answer #3 (95 Votes)

12/30/2011 17:18:17
$first = explode("/", $string)[0];
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.