【发布时间】:2011-04-11 21:04:24
【问题描述】:
$variable = 'put returns between paragraphs';
这个变量的值每次改变。
如何在最后一个单词前添加一些文字?
比如,如果我们想添加'and',结果应该是(对于这个例子):
$variable = 'put returns between and paragraphs';
【问题讨论】:
$variable = 'put returns between paragraphs';
这个变量的值每次改变。
如何在最后一个单词前添加一些文字?
比如,如果我们想添加'and',结果应该是(对于这个例子):
$variable = 'put returns between and paragraphs';
【问题讨论】:
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,这个算法似乎很合理。
$addition = 'and';
$variable = 'put returns between paragraphs';
$new_variable = preg_replace('/ ([^ ]+)$/', ' ' . $addition . ' $1', $variable);
【讨论】:
* 替换为+。
你可以使用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(),但是当你可以使用正则表达式时,为什么还要浪费更多的内存并调用另一个函数呢?:-)
【讨论】:
您可以使用 strrpos() 函数找到 last 空格:
$variable = 'put returns between paragraphs';
$lastSpace = strrpos($variable, ' '); // 19
然后,取两个substrings(在最后一个空格之前和之后)并环绕“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())。因此,没有需要来处理数组、反转字符串或正则表达式 - 但你当然可以 :)
【讨论】:
trim() 可能是解决方案)。就哪种解决方案“更清洁”而言,这是非常主观的。上面的内容很容易评论(因此也很容易理解),而我自己也觉得正则表达式解决方案很简洁。
'put returns between paragraphs '(带有尾随空格),这将中断
trim() 放在那里。缺点是现在你自己增加了更多的开销和更多的内存使用。
另一种选择
<?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
用 s 代替 c
【讨论】: