我有一个字符串:
$string = "R 124 This is my message";
有时候,字符串可能会发生变化,例如:
$string = "R 1345255 This is another message";
使用PHP,最好的方法是如何删除前两个“单词”(例如,最初的“R”,然后是随后的数字)?
谢谢帮助!
我有一个字符串:
$string = "R 124 This is my message";
$string = "R 1345255 This is another message";
使用PHP,最好的方法是如何删除前两个“单词”(例如,最初的“R”,然后是随后的数字)?
谢谢帮助!
$string = explode (' ', $string, 3);
$string = $string[2];
必须比正则表达式快得多。
explode
或preg_split
(取决于单词分隔符的复杂性:它们总是一个空格吗?)
例如:$string = "R 124 This is my message";
$words = explode(' ', $string);
var_dump($words);
array
0 => string 'R' (length=1)
1 => string '124' (length=3)
2 => string 'This' (length=4)
3 => string 'is' (length=2)
4 => string 'my' (length=2)
5 => string 'message' (length=7)
然后,使用array_slice
函数,你可以只保留你想要的单词(而不是前两个):
$to_keep = array_slice($words, 2);
var_dump($to_keep);
这将提供:
array
0 => string 'This' (length=4)
1 => string 'is' (length=2)
2 => string 'my' (length=2)
3 => string 'message' (length=7)
最后,你将所有的部件组合起来:
$final_string = implode(' ', $to_keep);
var_dump($final_string);
这会导致...
string 'This is my message' (length=18)
explode
和/或preg_split
要长一点^^
尝试
$result = preg_replace('/^R \\d+ /', '', $string, 1);
$result = preg_replace('/^R\\x20\\d+\\x20/', '', $string, 1);
$string = preg_replace("/^\\w+\\s\\d+\\s(.*)/", '$1', $string);
$string = preg_replace('/^R\s+\d+\s*/', '', $string);