Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you get a string before a specific character in PHP?

The PHP substr() function is another way to get the substring before a space. It is slightly less favourable since it has to be used with the strpos() function to find the first occurrence of a particular character in the string.

How do you find the last occurrence of a substring in a string in PHP?

The strrpos() function finds the position of the last occurrence of a string inside another string. Note: The strrpos() function is case-sensitive. Related functions: strpos() - Finds the position of the first occurrence of a string inside another string (case-sensitive)


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

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.


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

What about this :

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

Simply add a '/' to the end of mystring so you can be sure there is at least one ;)


Late is better than never. php has a predefined function for that. here is that good way.

strstr

if you want to get the part before match just set before_needle (3rd parameter) to true http://php.net/manual/en/function.strstr.php

function not_strtok($string, $delimiter)
{    
    $buffer = strstr($string, $delimiter, true);

    if (false === $buffer) {
        return $string;
    }

    return $buffer;
}

var_dump(
    not_strtok('st/art/page', '/')
);

One-line version of the accepted answer:

$out=explode("/", $mystring, 2)[0];

Should work in php 5.4+


This is probably the shortest example that came to my mind:

list($first) = explode("/", $mystring);

1) list() will automatically assign string until "/" if delimiter is found
2) if delimiter "/"is not found then the whole string will be assigned

...and if you get really obsessed with performance, you may add extra parameter to explode explode("/", $mystring, 2) which limits maximum of the returned elements.