faq
faq

Reputation: 3086

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 Third

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?

Upvotes: 1

Views: 1044

Answers (3)

RiaD
RiaD

Reputation: 47658

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);

Upvotes: 1

sberry
sberry

Reputation: 132138

$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.

Upvotes: 4

Ruslan Polutsygan
Ruslan Polutsygan

Reputation: 4461

Use regular expressions

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

Upvotes: 0

Related Questions