Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace last word in string

$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';
like image 396
James Avatar asked Sep 13 '10 20:09

James


Video Answer


1 Answers

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 :)

like image 132
jensgram Avatar answered Nov 17 '22 07:11

jensgram