Maybe really simple, but I can't get my head around how to use str_replace
to do the following on multiple phrases:
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:
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:
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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.