开发者

How to find (and replace) words with capital letters from a string?

$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 Th开发者_JS百科ird

Well the illustration speaks for itself. I want to select all words with capital letters (not words that start with capital letter) and replace with something in front of it. Any ideas?


$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

The regular expression being used says:

\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

Then, in the replacement

\\1, replace with the captured group.


str_replace just replace specific string to other specific one. You may use preg_replace

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


Use regular expressions

http://php.net/manual/en/function.preg-replace.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜