$variable = 'put returns between paragraphs';
这个变量的值每次都会改变。
如何在最后一个单词之前添加一些文本?
比如,如果我们想要添加'and'
,那么结果应该是(对于这个例子):
$variable = 'put returns between and paragraphs';
strrpos()
函数来找到最后一个空格。$variable = 'put returns between paragraphs';
$lastSpace = strrpos($variable, ' '); // 19
$before = substr($variable, 0, $lastSpace); // 'put returns between'
$after = substr($variable, $lastSpace); // ' paragraphs' (note the leading whitespace)
$result = $before . ' and' . $after;
strrpos()
和substr()
)。因此,没有必要使用数组、反转字符串或正则表达式 - 但当然你可以使用 :)preg_replace()
函数:$add = 'and';
$variable = 'put returns between paragraphs';
echo preg_replace("~\W\w+\s*$~", ' ' . $add . '\\0', $variable);
输出:
put returns between and paragraphs
$variable = 'put returns between paragraphs '
,它将中断)。当然,您可以使用 trim()
,但为什么要浪费更多内存并调用另一个函数,当您可以使用正则表达式来完成呢? :-)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.
strrpos
,这个算法似乎相当合理。 - erisco$addition = 'and';
$variable = 'put returns between paragraphs';
$new_variable = preg_replace('/ ([^ ]+)$/', ' ' . $addition . ' $1', $variable);
*
替换为 +
。 - jensgram另一种选择
<?php
$v = 'put returns between paragraphs';
$a = explode(" ", $v);
$item = "and";
array_splice($a, -1, 0, $item);
echo implode(" ",$a);
?>
替换最后一个字母
<?php
$txt = "what is c";
$count = strlen($txt);
$txt[$count -1] = "s";
echo $txt;
// output: what is s
将 c 替换为 s
trim()
函数可能是解决方案)。就“更干净”的解决方案而言,这是高度主观的。上述方法易于注释(因此易于理解),而我个人也认为正则表达式解决方案也很整洁。 - jensgramtrim()
。缺点是现在你增加了更多的开销和内存使用。 - NullUserException