替换字符串中的最后一个字

时间:2010-09-13 20:39:06

标签: php string replace

$variable = 'put returns between paragraphs';

每次更改时此变量的值。

如何在最后一个单词之前添加一些文字?


就像,如果我们要添加'and',结果应该是(对于此示例):

$variable = 'put returns between and paragraphs';

5 个答案:

答案 0 :(得分:10)

您可以使用strrpos()功能找到 last 空格:

$variable = 'put returns between paragraphs';
$lastSpace = strrpos($variable, ' '); // 19

然后,取两个substrings(在最后一个空格之前和之后)并包围'和':

$before = substr(0, $lastSpace); // 'put returns between'
$after = substr($lastSpace); // ' paragraphs' (note the leading whitespace)
$result = $before . ' and' . $after;

修改
虽然没有人想要破解子字符串索引,但这是一个非常基本任务,PHP为其提供了有用的功能(特别是strrpos()substr())。因此,没有需要来处理数组,反向字符串或正则表达式 - 但你可以,当然:)

答案 1 :(得分:2)

您可以使用preg_replace()

$add = 'and';
$variable = 'put returns between paragraphs';    
echo preg_replace("~\W\w+\s*$~", ' ' . $add . '\\0', $variable);

打印:

put returns between and paragraphs

这将忽略尾随空格,@ jensgram的解决方案没有。 (例如:如果你的字符串是$variable = 'put returns between paragraphs ',它就会中断。当然你可以使用trim(),但为什么要浪费更多的内存并在你用正则表达式时调用另一个函数?: - )< / p>

答案 2 :(得分:1)

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.

答案 3 :(得分:1)

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

答案 4 :(得分:1)

另一个选项

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