How to exclude single-lettered title case words in a string?

Tags: ,



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!

Answer

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.



Source: stackoverflow