Splitting strings in PHP and get last part

前端 未结 13 2339
无人及你
无人及你 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条回答
  •  猫巷女王i
    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
    

提交回复
热议问题