我已经尝试了一些事情来完成最后一部分我做了这个:
$string = 'Sim-only 500 | Internet 2500';
preg_replace("Sim-Only ^([1-9]|[1-9][0-9]|[1-9][0-9][0-9][0-9])$ | Internet ","",$string
AND
preg_match("/[^ ]*$/","",{abo_type[1]})
Run Code Online (Sandbox Code Playgroud)
第一个不起作用,第二个返回一个数组,但真正需要字符串.
MLe*_*vre 44
如果你在句子的最后一个单词之后,为什么不做这样的事呢?
$string = '?Sim-only 500 ?| Internet 2500';
$pieces = explode(' ', $string);
$last_word = array_pop($pieces);
echo $last_word;
Run Code Online (Sandbox Code Playgroud)
我不建议使用正则表达式,因为它是不必要的,除非你真的想要出于某种原因.
$string = 'Retrieving the last word of a string using PHP.';
preg_match('/[^ ]*$/', $string, $results);
$last_word = $results[0]; // $last_word = PHP.
Run Code Online (Sandbox Code Playgroud)
substr()他们给出的方法可能更好
$string = 'Retrieving the last word of a string using PHP.';
$last_word_start = strrpos($string, ' ') + 1; // +1 so we don't include the space in our result
$last_word = substr($string, $last_word_start); // $last_word = PHP.
Run Code Online (Sandbox Code Playgroud)
它更快,虽然它确实没有在这样的事情上产生那么大的差异.如果您经常需要知道100,000字符串的最后一个字,那么您应该以不同的方式处理它.
小智 9
这应该适合你:
$str = "fetch the last word from me";
$last_word_start = strrpos ( $str , " ") + 1;
$last_word_end = strlen($str) - 1;
$last_word = substr($str, $last_word_start, $last_word_end);
Run Code Online (Sandbox Code Playgroud)
这取决于您尝试执行的操作(从您的描述中很难理解),但要从字符串中获取最后一个单词,您可以执行以下操作:
$split = explode(" ", $string);
echo $split[count($split)-1];
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅如何获取字符串的最后一个单词。