$variable = 'put returns between paragraphs';
Value of this variable everytime changes.
How to add some text before the last word?
Like, if we want to add 'and'
, the result should be (for this example):
$variable = 'put returns between and paragraphs';
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With