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

PhpStringSubstring

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

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.

Solution 3 - Php

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

Solution 4 - Php

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 ;)

Solution 5 - Php

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', '/')
);

Solution 6 - Php

One-line version of the accepted answer:

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

Should work in php 5.4+

Solution 7 - Php

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.

Solution 8 - Php

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.

Solution 9 - Php

The function strstr() in PHP 5.3 should do this job.. The third parameter however should be set to true..

But if you're not using 5.3, then the function below should work accurately:

function strbstr( $str, $char, $start=0 ){
	if ( isset($str[ $start ]) && $str[$start]!=$char ){
		return $str[$start].strbstr( $str, $char, $start+1 );
	}
}

I haven't tested it though, but this should work just fine.. And it's pretty fast as well

Solution 10 - Php

Using current on explode would ease the process.

 $str = current(explode("/", $str, 2));

Solution 11 - Php

You could create a helper function to take care of that:

/**
 * Return string before needle if it exists.
 *
 * @param string $str
 * @param mixed $needle
 * @return string
 */
function str_before($str, $needle)
{
    $pos = strpos($str, $needle);
  
    return ($pos !== false) ? substr($str, 0, $pos) : $str;
}

Here's a use case:

$sing = 'My name is Luka. I live on the second floor.';

echo str_before($sing, '.'); // My name is Luka

Solution 12 - Php

$string="kalion/home/public_html";

$newstring=( stristr($string,"/")==FALSE ) ? $string : substr($string,0,stripos($string,"/"));

Solution 13 - Php

why not use:

function getwhatiwant($s)
{
    $delimiter='/';
    $x=strstr($s,$delimiter,true);
    return ($x?$x:$s);
}

OR:

   function getwhatiwant($s)
   {
       $delimiter='/';
       $t=explode($delimiter, $s);
       return ($t[1]?$t[0]:$s);
   }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionanon355079View Question on Stackoverflow
Solution 1 - PhpjmarceliView Answer on Stackoverflow
Solution 2 - PhpgnudView Answer on Stackoverflow
Solution 3 - PhpAndyBrandyView Answer on Stackoverflow
Solution 4 - PhpIRCFView Answer on Stackoverflow
Solution 5 - PhpaimmeView Answer on Stackoverflow
Solution 6 - Php111View Answer on Stackoverflow
Solution 7 - PhppavlovichView Answer on Stackoverflow
Solution 8 - Phpt00nyView Answer on Stackoverflow
Solution 9 - PhpRonaldView Answer on Stackoverflow
Solution 10 - Phpuser1518659View Answer on Stackoverflow
Solution 11 - Phpuser5134807View Answer on Stackoverflow
Solution 12 - PhpkalionView Answer on Stackoverflow
Solution 13 - Phpuser1123382View Answer on Stackoverflow