0

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 (i.e. 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

Community
  • 1
  • 1
user3544484
  • 761
  • 1
  • 9
  • 17

3 Answers3

3

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);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
1

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";
alexis
  • 48,685
  • 16
  • 101
  • 161
0
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");
Sachin Tyagi
  • 133
  • 6
  • need to put here your string variable besides "I Love London Living near Birmingham Playing by Scotland" – Sachin Tyagi Aug 31 '15 at 18:08
  • 1
    While this code may answer the question, it would be better to include some context, explain how it works, and describe when to use it. Code-only answers are not useful in the long run. – ryanyuyu Aug 31 '15 at 18:50