11

与えられた

 $str = "asd/fgh/jkl/123

最後のスラッシュの後に文字列の一部を取得したい場合は、関数を使用できますstrrchr()か? 関数ではないphpで、文字列部分を取得するには、最後のスラーの前に、それは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;

output: 123;

explode() converts the string into an array using "/" as a separator (you can pick the separator)

end() returns the last item of the array

于 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 に答える