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

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

2 Comments

need to put here your string variable besides "I Love London Living near Birmingham Playing by Scotland"
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.