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

Jam*_*mes 6 php string replace

$variable = 'put returns between paragraphs';
Run Code Online (Sandbox Code Playgroud)

每次变化时此变量的值.

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


就像,如果我们想要添加'and',结果应该是(对于这个例子):

$variable = 'put returns between and paragraphs';
Run Code Online (Sandbox Code Playgroud)

jen*_*ram 10

您可以使用以下函数找到最后一个空格strrpos():

$variable = 'put returns between paragraphs';
$lastSpace = strrpos($variable, ' '); // 19
Run Code Online (Sandbox Code Playgroud)

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

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

编辑
虽然没有人愿意惹子指标,这是一个非常基本的任务,其PHP附带了有用的功能(specificly strrpos()substr()).因此,没有必要兼顾数组,字符串颠倒或正则表达式-但你可以,当然:)


Nul*_*ion 2

您可以使用preg_replace()

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

印刷:

put returns between and paragraphs
Run Code Online (Sandbox Code Playgroud)

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

  • 我无法确定来源,但我曾经听到过这样一句话“我遇到了问题并决定使用正则表达式。现在我有两个问题” (2认同)