替换字符串中的最后一个单词。

6
$variable = 'put returns between paragraphs';

这个变量的值每次都会改变。

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


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

$variable = 'put returns between and paragraphs';
6个回答

11
你可以使用strrpos()函数来找到最后一个空格。
$variable = 'put returns between paragraphs';
$lastSpace = strrpos($variable, ' '); // 19

然后,取出两个子字符串(最后一个空格之前和之后的部分),并在其周围加上'and'。
$before = substr($variable, 0, $lastSpace); // 'put returns between'
$after = substr($variable, $lastSpace); // ' paragraphs' (note the leading whitespace)
$result = $before . ' and' . $after;

编辑
虽然没有人想要处理子字符串索引,但这是一个非常基本的任务,PHP提供了一些有用的函数(特别是strrpos()substr())。因此,没有必要使用数组、反转字符串或正则表达式 - 但当然你可以使用 :)

1
@NullUserException 你说得对,可能是由于末尾的空格(使用trim()函数可能是解决方案)。就“更干净”的解决方案而言,这是高度主观的。上述方法易于注释(因此易于理解),而我个人也认为正则表达式解决方案也很整洁。 - jensgram
1
我认为我的正则表达式解决方案比这个更简洁。此外,您可以调整它以使用不同的分隔符或忽略尾随空格(就像我的解决方案一样)。如果您的字符串是“在段落之间放置回车”(带有尾随空格),则这将会出错。 - NullUserException
@jensgram 是的,我知道你可以在那里放置 trim()。缺点是现在你增加了更多的开销和内存使用。 - NullUserException
@NullUserException 开销?是的,我想是有的。内存使用?在几乎任何“正常”的情况下,我认为它是可以忽略不计的。此外,我们甚至不知道尾随空格是否可能成为一个问题。 - jensgram
@jensgram “就哪个解决方案更“干净”,这是非常主观的。” 这就是为什么我说“认为我的正则表达式解决方案更干净”;-) - NullUserException

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(),但为什么要浪费更多内存并调用另一个函数,当您可以使用正则表达式来完成呢? :-)

2
我无法确认出处,但我曾经听过这句伟大的名言:“我有一个问题,决定使用正则表达式。现在我有两个问题了。” - Zak
如何在您的解决方案中添加一些HTML而不是使用“and”? - James
@Zak 如果你理解正则表达式,并且知道它能做什么,不能做什么,那就不是问题。 - NullUserException

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.

1
当然这并非必须,但很简单,而且这个简单的问题明显需要一个简单易懂的答案,用通俗易懂的英语(而非代码)来解释如何按照逻辑思路解决问题。 - Zak
如果没有 strrpos,这个算法似乎相当合理。 - erisco

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

考虑在模式中将 * 替换为 + - jensgram
@jensgram 谢谢你发现了那个。 - user142162

1

另一种选择

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

0

替换最后一个字母

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

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

echo $txt;
// output: what is s

将 c 替换为 s


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接