Reputation: 85
I have a database table that stores wishes from users. From that, I'd like to extract any title case words that they have submitted. I was able to obtain this output, however it includes single-lettered words such as I and A. Below is my current code, supposed we have a wish:
$x = "I wish for choice cards spelling PREJOIN 'coz I love Nature.";
preg_match_all('/\b([A-Z]+)\b/', $x, $matches);
array_shift($matches[0]);
foreach($matches[0] as $w) {
$x = str_replace($w, "<b>$w</b>", $x);
}
echo $x;
The goal is to highlight the word PREJOIN, but with that code, it also highlights the word I where it shouldn't. Specifying the word is not possible as the wishes are being fetched from the database randomly, I just specified the value of $x
as an example. How should the code be written with only highlighting the word PREJOIN?
Current output:
I
wish for choice cards spelling PREJOIN
'coz I
love Nature.
Desired output:
I wish for choice cards spelling PREJOIN
'coz I love Nature.
Many thanks in advance!
Upvotes: 1
Views: 76
Reputation: 7713
Just take preg_replace() with the regular expression of Tim.
$x = "I wish for choice cards spelling PREJOIN 'coz I love Nature. A test with AB and XXX.";
$new = preg_replace('/\b[A-Z]{2,}\b/', '<b>$0</b>',$x);
echo $new;
Output:
I wish for choice cards spelling PREJOIN 'coz I love Nature. A test with AB and XXX.
Upvotes: 0
Reputation: 522817
Well assuming the exclusion only applies to single capital letter words, you may match on \b[A-Z]{2,}\b
:
preg_match_all('/\b([A-Z]{2,})\b/', $x, $matches);
However, if the intention is to exclude things like specific pronouns e.g. I
, then you might do better to come up with a blacklist of single letter which should be excluded.
Full script:
$x = "I wish for choice cards spelling PREJOIN 'coz I love Nature.";
preg_match_all('/\b[A-Z]{2,}\b/', $x, $matches);
print_r($matches[0]);
This prints:
Array
(
[0] => PREJOIN
)
Upvotes: 3