2010-09-13 113 views
6
$variable = 'put returns between paragraphs'; 

每次更改此变量的值。替换字符串中的最后一个字

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


一样,如果我们要添加'and',结果应该是(在这个例子中):

$variable = 'put returns between and paragraphs'; 

回答

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 2010-09-13 20:52:40

+0

如何在解决方案中添加一些html而不是'and'? – James 2010-09-13 20:53:05

+0

@Zak如果你理解了正则表达式并不是一个问题,并且知道它可以做什么,不能做什么。 – NullUserException 2010-09-13 20:54:15

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. 
+0

逆转,很多时候是完全unnessecary – GSto 2010-09-13 20:45:35

+1

当然这是不必要,但很简单,这个简单的问题显然需要简单易懂的答案,用简单的英语(而不是代码)来解释如何解决问题的逻辑过程。 – Zak 2010-09-13 20:48:15

+0

如果你没有'strrpos',这个算法看起来很合理。 – erisco 2010-09-13 21:02:49

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

考虑用模式中的'+'替换'*'。 – jensgram 2010-09-13 20:56:09

+0

@jensgram谢谢你。 – 2010-09-13 20:58:58

10

您可以找到?最后空白使用strrpos()功能:

$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附带了有用的功能(specificly strrpos()substr())。因此,有没有需要兼顾阵列,颠倒字符串或正则表达式 - 但你可以,当然:)

+0

杰克斯伟大的答案。 – Zak 2010-09-13 20:51:25

+1

@NullUserException你说的可能是一个可能的尾部空白('trim()'可能是解决方案)。就哪个解决方案“更清洁”而言,这是非常主观的。上述内容很容易评论(因此易于理解),而我自己也可以找到正则表达式解决方案。 – jensgram 2010-09-13 20:55:15

+1

我发现我的正则表达式解决方案比这更清洁。此外,你可以调整它使用不同的分隔符,或忽略尾随的空白(像我一样)。如果你的字符串是''在段落之间放置返回'(带有空白尾部) – NullUserException 2010-09-13 20:56:47

1

另一种选择

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