可能真的很简单,但是我不知道如何使用str_replace
在多个短语上做以下操作:
注意:它总是我想保留的最后一个词(即伦敦,伯明翰&苏格兰或其他地区)。
<<p> 例子短语/strong>我爱伦敦
住在伯明翰附近
苏格兰演奏
要转化为:
In London Today
In Birmingham Today
今日苏格兰
谢谢
如果没有更多的代码,您可能无法使用str_replace()
:
preg_match('/w+$/', $string, $match);
echo $match[0];
或者替换为
$result = preg_replace('/.*?(w+)$/', 'In $1 Today', $string);
使用正则表达式和preg_replace()
一步完成:
print preg_replace('/.* (w+)W*/', 'In 1 today', "I love London");
通过忽略最后一个单词后面的标点或空格,我使它比你预期的更健壮。
或者,对整个字符串列表使用相同的regexp:
$data = array("I love London",
"I live in Birmingham!",
"Living near Birmingham!",
"Playing by Scotland..."
);
$results = preg_replace('/.* (w+)W*/', 'In 1 today', $data);
foreach ($results as $string)
print $string, "n";
echo str_replace(array("I Love London","Living near Birmingham","Playing by Scotland"), array("In London Today","In Birmingham Today","In Scotland Today"), "I Love London Living near Birmingham Playing by Scotland");