如何从字符串中用大写字母查找(和替换)单词?

时间:2011-08-27 20:47:20

标签: php string replace

$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

这个例子说明了一切。我想选择所有带大写字母的单词(不是以大写字母开头的单词),而是用前面的内容替换。有什么想法吗?

3 个答案:

答案 0 :(得分: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.

答案 1 :(得分:1)

str_replace只需将特定字符串替换为其他特定字符串即可。您可以使用preg_replace

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

答案 2 :(得分:0)