Splitting strings in PHP and get last part

前端 未结 13 2279
无人及你
无人及你 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:44

    This code will do that

    <?php
    $string = 'abc-123-xyz-789';
    $output = explode("-",$string);
    echo $output[count($output)-1];
    ?>
    
    0 讨论(0)
  • 2020-12-08 04:45

    As per this post:

    end((explode('-', $string)));
    

    which won't cause E_STRICT warning in PHP 5 (PHP magic). Although the warning will be issued in PHP 7, so adding @ in front of it can be used as a workaround.

    0 讨论(0)
  • 2020-12-08 04:47

    Since explode() returns an array, you can add square brackets directly to the end of that function, if you happen to know the position of the last array item.

    $email = 'name@example.com';
    $provider = explode('@', $email)[1];
    echo $provider; // example.com
    

    Or another way is list():

    $email = 'name@example.com';
    list($prefix, $provider) = explode('@', $email);
    echo $provider; // example.com
    

    If you don't know the position:

    $path = 'one/two/three/four';
    $dirs = explode('/', $path);
    $last_dir = $dirs[count($dirs) - 1];
    echo $last_dir; // four
    
    0 讨论(0)
  • 2020-12-08 04:51
    $string = 'abc-123-xyz-789';
    $exploded = explode('-', $string);
    echo end($exploded);
    

    EDIT::Finally got around to removing the E_STRICT issue

    0 讨论(0)
  • 2020-12-08 04:56

    Just Call the following single line code:

     $expectedString = end(explode('-', $orignalString));
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题