11

给定

 $str = "asd/fgh/jkl/123

如果我们想在最后一个斜杠之后获取字符串片段,我们可以使用函数strrchr()对吗?在 php 中不起作用,要在最后一个 slah 之前获取字符串片段,即asd/fgh/jkl

我知道这可以通过正则表达式或其他方式进行,我在问内部功能?

4

4 回答 4

22

您可以使用

$str = "asd/fgh/jkl/123";
echo substr($str, 0,strrpos($str, '/'));

输出

asd/fgh/jkl
于 2012-11-20T11:08:12.910 回答
2
$str = "asd/fgh/jkl/123";

$lastPiece = end(explode("/", $str));

echo $lastPiece;

输出:123;

explode()使用“/”作为分隔符将字符串转换为数组(您可以选择分隔符)

end()返回数组的最后一项

于 2012-11-20T10:58:23.290 回答
1

您可以通过以下方式做到这一点:

explode— 逐个字符串拆分(文档

$pieces = explode("/", $str );

例子

$str = "asd/fgh/jkl/123";
$pieces = explode("/", $str );
print_r($pieces);

$count= count($pieces);
echo $pieces[$count-1]; //or
echo  end($pieces);

键盘

于 2012-11-20T10:54:46.507 回答
0

使用这个强大的自定义功能

 /* $position = false and $sub = false show result of before first occurance of $needle */
 /* $position = true and $sub false show result of before last occurance of $needle     */
 /* $position = false and $sub = true show result of after first occurance of $needle   */  
 /* $position = true and $sub true show result of after last occurance of         $needle       */


function CustomStrStr($str,$needle,$position = false,$sub = false)
{
$Isneedle = strpos($str,$needle);
if ($Isneedle === false)
return false;

    $needlePos =0;
    $return;
    if ( $position === false )
        $needlePos = strpos($str,$needle);
    else
        $needlePos = strrpos($str,$needle);

    if ($sub === false)
        $return = substr($str,0,$needlePos);
    else
        $return = substr($str,$needlePos+strlen($needle));

return $return;         
}
于 2012-11-20T11:12:34.153 回答