PHP で文字列を「-」で分割し、最後の部分を取得する必要があります。
だからこれから:
abc-123-xyz-789
私は得ることを期待しています
「789」
これは私が思いついたコードです:
substr(strrchr($urlId, '-'), 1)
以下を除いて、正常に動作します。
入力文字列に「-」が含まれていない場合は、次のように文字列全体を取得する必要があります。
123
私は戻る必要があります
123
そしてそれはできるだけ速くする必要があります。
split($pattern,$string)特定のパターンまたは正規表現内で文字列を分割します(5.3.0 以降は非推奨です)。preg_split($pattern,$string)指定された正規表現パターン内で文字列を分割しますexplode($pattern,$string)指定されたパターン内で文字列を分割するend($arr)配列の最後の要素を取得するそう:
end(split('-',$str))
end(preg_split('/-/',$str))
$strArray = explode('-',$str)
$lastElement = end($strArray)
-分離された文字列の最後の要素を返します。
そして、これを行うためのハードコアな方法があります:
$str = '1-2-3-4-5';
echo substr($str, strrpos($str, '-') + 1);
// | '--- get the last position of '-' and add 1(if don't substr will get '-' too)
// '----- get the last piece of string after the last occurrence of '-'
他の人が言及したように、結果をexplode()変数に代入しないと、次のメッセージが表示されます。
E_STRICT: 厳格な基準: 変数のみを参照渡しする必要があります
正しい方法は次のとおりです。
$words = explode('-', 'hello-world-123');
$id = array_pop($words); // 123
$slug = implode('-', $words); // hello-world
この投稿に従って:
end((explode('-', $string)));
PHP 5 ではE_STRICT警告が発生しません( PHP マジック)。PHP 7 では警告が発行されますが、その前に追加すること@で回避できます。
このコードはそれを行います
<?php
$string = 'abc-123-xyz-789';
$output = explode("-",$string);
echo $output[count($output)-1];
?>