给出
$str = "asd/fgh/jkl/123
如果我们想在最后一次斜杠后得到字符串,我们可以使用函数strrchr()
吗?
在php中没有函数,要获取字符串片段,在最后一个slah之前,即asd/fgh/jkl
?
我知道这可以通过正则表达式或其他方式,我问内部函数?
答案 0 :(得分:18)
您可以使用
$str = "asd/fgh/jkl/123";
echo substr($str, 0,strrpos($str, '/'));
输出
asd/fgh/jkl
答案 1 :(得分:2)
$str = "asd/fgh/jkl/123";
$lastPiece = end(explode("/", $str));
echo $lastPiece;
输出:123;
explode()使用" /"将字符串转换为数组作为分隔符(您可以选择分隔符)
end()返回数组的最后一项
答案 2 :(得分:0)
您可以通过以下方式执行此操作:
explode
- 按字符串(Documentation)
$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);
答案 3 :(得分: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;
}