Replace last word in string
You can find the last whitespace using the strrpos()
function:
$variable = 'put returns between paragraphs';
$lastSpace = strrpos($variable, ' '); // 19
Then, take the two substrings (before and after the last whitespace) and wrap around the 'and':
$before = substr($variable, 0, $lastSpace); // 'put returns between'
$after = substr($variable, $lastSpace); // ' paragraphs' (note the leading whitespace)
$result = $before . ' and' . $after;
EDIT
Although nobody wants to mess with substring indexes this is a very basic task for which PHP ships with useful functions (specificly strrpos()
and substr()
). Hence, there's no need to juggle arrays, reversed strings or regexes - but you can, of course :)
You can use preg_replace()
:
$add = 'and';
$variable = 'put returns between paragraphs';
echo preg_replace("~\W\w+\s*$~", ' ' . $add . '\\0', $variable);
Prints:
put returns between and paragraphs
This will ignore trailing whitespaces, something @jensgram's solution doesn't. (eg: it will break if your string is $variable = 'put returns between paragraphs '
. Of course you can use trim()
, but why bother to waste more memory and call another function when you can do it with regex ? :-)