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(0, $lastSpace); // 'put returns between'
$after = substr($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 :)