Splitting strings in PHP and get last part

前端 未结 13 2345
无人及你
无人及你 2020-12-08 04:39

I need to split a string in PHP by \"-\" and get the last part.

So from this:

abc-123-xyz-789

I expect to get

13条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-08 04:57

    The accepted answer has a bug in it where it still eats the first character of the input string if the delimiter is not found.

    $str = '1-2-3-4-5';
    echo substr($str, strrpos($str, '-') + 1);
    

    Produces the expected result: 5

    $str = '1-2-3-4-5';
    echo substr($str, strrpos($str, ';') + 1);
    

    Produces -2-3-4-5

    $str = '1-2-3-4-5';
    if (($pos = strrpos($str, ';')) !== false)
        echo substr($str, $pos + 1);
    else
        echo $str;
    

    Produces the whole string as desired.

    3v4l link

提交回复
热议问题