views:

1056

answers:

3

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?

+11  A: 

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.

gnud
+1 Good answer.
Franz
+1 Thanks for the answer. It worked :) But one question. I am only able to do this -> `$arr = explode('/',$mystring,2); echo $arr[0];`. I am unable to get the first string in one statement itself - `echo explode('/',$mystring,2)[0];`. Since explode returns an array, I should be able to do it right? But I get an error. Any suggestions?
Senthil
No, you cannot do that.
Franz
Php doesn't like you indexing into return values from functions.
gnud
oh. okay. would have been nice if it was possible.
Senthil
`list($first,) = explode("/", $string, 2);`
roddik
+1  A: 

I think this should work?

substr($mystring, 0, (($pos = (strpos($mystring, '/') !== false)) ? $pos : strlen($mystring)));
Franz
A: 

You can try using a regex like this:

$s = preg_replace('|/.*|', '', $s);

sometimes, regex are slower though, so if performance is an issue, make sure to benchmark this properly and use an other alternative with substrings if it's more suitable for you.

t00ny