phpstringreplace

Inject a word before the last word in a 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';

Solution

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