简体   繁体   English

PHP字符串替换删除并在最后添加单词

[英]php string replace remove & add word at the end

Maybe really simple, but I can't get my head around how to use str_replace to do the following on multiple phrases: 也许真的很简单,但是我无法理解如何使用str_replace对多个短语执行以下操作:

Note: It is always the last word that I want to retain (ie London, Birmingham & Scotland or any others). 注意:这始终是我要保留的最后一个字(即伦敦,伯明翰和苏格兰或其他任何地方)。

Example Phrases 短语示例

I Love London 我爱伦敦

Living near Birmingham 住在伯明翰附近

Playing by Scotland 苏格兰演奏

To be turned into: 要变成:

In London Today 今天在伦敦

In Birmingham Today 今天在伯明翰

In Scotland Today 今天在苏格兰

Thanks 谢谢

You're probably not going to be able to use str_replace() with out a lot more code: 您可能无法在没有更多代码的情况下使用str_replace()

preg_match('/\w+$/', $string, $match);
echo $match[0];

Or as an example replace: 或例如替换:

$result = preg_replace('/.*?(\w+)$/', 'In $1 Today', $string);

Use a regular expression and preg_replace() to do it in one step: 使用正则表达式和preg_replace()一步即可做到:

print preg_replace('/.* (\w+)\W*/', 'In \1 today', "I love London");

I made it a bit more robust than you anticipate, by ignoring any punctuation or spaces after the last word. 通过忽略最后一个单词之后的标点或空格,我使它比您预期的更健壮。

Or, to use the same regexp with a whole list of strings: 或者,将相同的正则表达式与整个字符串列表一起使用:

$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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM