PHP substring extraction. Get the string before th

2019-01-04 08:33发布

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?

14条回答
戒情不戒烟
2楼-- · 2019-01-04 08:36

One-line version of the accepted answer:

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

Should work in php 5.4+

查看更多
Rolldiameter
3楼-- · 2019-01-04 08:37

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', '/')
);
查看更多
仙女界的扛把子
4楼-- · 2019-01-04 08:38

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

查看更多
手持菜刀,她持情操
5楼-- · 2019-01-04 08:38

I think this should work?

substr($mystring, 0, (($pos = (strpos($mystring, '/') !== false)) ? $pos : strlen($mystring)));
查看更多
倾城 Initia
6楼-- · 2019-01-04 08:44

The most efficient solution is the strtok function:

strtok($mystring, '/')

For example:

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

and

$mystring = 'home';
$first = strtok($mystring, '/');
echo $first; // home
查看更多
狗以群分
7楼-- · 2019-01-04 08:46

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.

查看更多
登录 后发表回答