James
James

Reputation: 43647

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';

Upvotes: 6

Views: 6573

Answers (6)

ahmed khan
ahmed khan

Reputation: 35

Replace last letter

<?php
$txt = "what is c";

$count = strlen($txt);
$txt[$count -1] = "s";

echo $txt;
// output: what is s

replacing c with s

Upvotes: 0

jensgram
jensgram

Reputation: 31508

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

Upvotes: 11

user142162
user142162

Reputation:

$addition = 'and';
$variable = 'put returns between paragraphs';
$new_variable = preg_replace('/ ([^ ]+)$/', ' ' . $addition . ' $1', $variable);

Upvotes: 1

NullUserException
NullUserException

Reputation: 85468

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

Upvotes: 2

mcgrailm
mcgrailm

Reputation: 17640

another option

  <?php
  $v = 'put returns between paragraphs';
  $a = explode(" ", $v);
  $item = "and";
  array_splice($a, -1, 0, $item);
  echo  implode(" ",$a);
  ?>

Upvotes: 1

Zak
Zak

Reputation: 25205

1) reverse your string
2) find the first whitespace in the string.
3) chop off the remainder of the string.
4) reverse that, append your text
5) reverse and add back on the first portion of the string from step 3, including extra whitespace as needed.

Upvotes: 1

Related Questions