Franky Chanyau
Franky Chanyau

Reputation: 1010

Get string after first occurring forward slash

I have a string:

$uri = "start/test/go/";

Basically I need to know which regular expression and PHP function I can use to match the first item with a forward slash ("/") and remove it from the string. It should also work if the first item is not start and is anything else which might also have a space in it. So all these combination should work:

$uri = "start_my_test/test/go/";
$uri2 = "start my test/test/go/";

Then after the RegEx it should always return:

$newUri = "test/go/";

Oh and the other side of the string could be anything as well, So basically I want it to delete anything before the first occurrence of a forward slash.

Upvotes: 0

Views: 247

Answers (3)

brian_d
brian_d

Reputation: 11360

regex is too expensive an operation for what you need. use strpos and substr instead

$position = strpos($needle, $haystack);
if ( $position !== false ) {
  $result = substr($needle, $position + 1);
}

Upvotes: 0

08Hawkeye
08Hawkeye

Reputation: 246

Use strstr to find the first occurrence of a string in php.

That in itself should return the remainder of the string.

see here

Upvotes: 4

Ben Lee
Ben Lee

Reputation: 53319

$result = preg_replace('/^[^\/]*\//' , '', $subject);

This says "start at the beginning of the string" ^, "match any number of characters that are not a forward slash" [^\/]*, then match a single forward slash \/ -- and "replace the whole matched thing with nothing" ''.

Upvotes: 0

Related Questions