2011-08-27 163 views
1
$string = "WORD is the first HEJOU is the Second BOOM is the Third"; 
$sring = str_replce('???', '???<br>', $string); 
echo $string; // <br>WORD is the first <br>HEJOU is the Second <br>BOOM is the Third 

那麼這個例子說明了一切。我想選擇大寫字母的所有單詞(而不是以大寫字母開頭的單詞)並替換爲前面的內容。有任何想法嗎?如何從字符串中查找(並替換)大寫字母的單詞?

回答

4
$string = "WORD is the first HEJOU is the Second BOOM is the Third"; 
$string = preg_replace("#\b([A-Z]+)\b#", "<br>\\1", $string); 
echo $string; 

OUTOUT
<br>WORD is the first <br>HEJOU is the Second <br>BOOM is the Third

正則表達式表示:

\b - Match a word boundary, zero width 
[A-Z]+ - Match any combination of capital letters 
\b - Match another word boundary 
([A-Z]+) - Capture the word for use in the replacement 

然後,在更換

\\1, replace with the captured group. 
+0

'#'字符的用法是什麼? – user823959

+3

這只是一個分隔符。 '#'可以被另一個字符替換。/常見。我似乎總是使用# – sberry

+0

像RiaD使用〜代替。 – sberry

1

str_replace只需更換特定字符串的其他特定之一。您可以使用正在使用preg_replace

print preg_replace('~\b[A-Z]+\b~','<br>\\0',$string); 
+0

我認爲你的意思是用'\\ 1'而不是'\\ 0'的反向引用來替換,它與整個輸入相匹配。 – sberry

+1

@sberry,你可以在我的正則表達式中看到\ 1。 \\ 0是完全匹配的正則表達式。它的工作原理 – RiaD

相關問題