php string replace remove & add word at the end
php string replace remove & add word at the end
也许真的很简单,但我无法理解如何使用 str_replace
对多个短语执行以下操作:
注意:它始终是我要保留的最后一个词(即伦敦、伯明翰和苏格兰或任何其他词)。
示例短语
I Love London
Living near Birmingham
Playing by Scotland
待转化为:
In London Today
In Birmingham Today
In Scotland Today
谢谢
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");
如果没有更多代码,您可能无法使用 str_replace()
:
preg_match('/\w+$/', $string, $match);
echo $match[0];
或者作为示例替换:
$result = preg_replace('/.*?(\w+)$/', 'In Today', $string);
使用正则表达式和preg_replace()
一步完成:
print preg_replace('/.* (\w+)\W*/', 'In today', "I love London");
我忽略了最后一个词后的任何标点符号或空格,使其比您预期的更健壮。
或者,对整个字符串列表使用相同的正则表达式:
$data = array("I love London",
"I live in Birmingham!",
"Living near Birmingham!",
"Playing by Scotland..."
);
$results = preg_replace('/.* (\w+)\W*/', 'In today', $data);
foreach ($results as $string)
print $string, "\n";
也许真的很简单,但我无法理解如何使用 str_replace
对多个短语执行以下操作:
注意:它始终是我要保留的最后一个词(即伦敦、伯明翰和苏格兰或任何其他词)。
示例短语
I Love London
Living near Birmingham
Playing by Scotland
待转化为:
In London Today
In Birmingham Today
In Scotland Today
谢谢
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");
如果没有更多代码,您可能无法使用 str_replace()
:
preg_match('/\w+$/', $string, $match);
echo $match[0];
或者作为示例替换:
$result = preg_replace('/.*?(\w+)$/', 'In Today', $string);
使用正则表达式和preg_replace()
一步完成:
print preg_replace('/.* (\w+)\W*/', 'In today', "I love London");
我忽略了最后一个词后的任何标点符号或空格,使其比您预期的更健壮。
或者,对整个字符串列表使用相同的正则表达式:
$data = array("I love London",
"I live in Birmingham!",
"Living near Birmingham!",
"Playing by Scotland..."
);
$results = preg_replace('/.* (\w+)\W*/', 'In today', $data);
foreach ($results as $string)
print $string, "\n";