2010-09-13 90 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); 
    ?> 
相關問題