Reputation: 145
i need to change uppercase matches to bold but including colon
$str = "GOOD MORNING:";
preg_replace("/\b([A-Z]{2,}(\s[A-Z]{2,})?)\b/", "<b>$1</b>", $str);
it returns:
<b>GOOD MORNING</b>:
it should return:
<b>GOOD MORNING:</b>
all my tries made my replace stop wroking
Upvotes: 1
Views: 84
Reputation: 7795
preg_replace("/([A-Z]{2,}\s[A-Z]{2,}:?)/", "<b>$1</b>", $str);
Output:
<b>GOOD MORNING:</b>
Upvotes: 0
Reputation: 22382
There are a few different ways:
Any of the following should suffice:
preg_replace("/([A-Z:]{2,}(\s[A-Z:]{2,})?)/", "<b>$1</b>", $str);
preg_replace("/([A-Z]{2,}(\s[A-Z:]{2,})?)/", "<b>$1</b>", $str);
preg_replace("/([A-Z]{2,}(\s[A-Z]{2,})?:?)/", "<b>$1</b>", $str);
Here is my test output:
<?php
$str = "GOOD MORNING:";
echo preg_replace('/([A-Z:]{2,}(\s+[A-Z:]{2,})?)/', "<b>$1</b>", $str);
echo preg_replace('/([A-Z]{2,}(\s+[A-Z:]{2,})?)/', "<b>$1</b>", $str);
echo preg_replace('/([A-Z]{2,}(\s+[A-Z]{2,})?:?)/', "<b>$1</b>", $str);
?>
Midget:~ masud$ php foo.php
<b>GOOD MORNING:</b><b>GOOD MORNING:</b><b>GOOD MORNING:</b>
Upvotes: 0
Reputation: 89567
You must add the colon in your character class. or just before the closing parenthesis of you capturing group (with a question mark if you want it optional).
$str = preg_replace('~[A-Z]{2,}(?:\s[A-Z]{2,})?:?~', '<b>$0</b>', $str);
Notice: word boundaries are not needed here, since the regex engine begin from the left and your quantifier {2,}
is greedy)
Upvotes: 1
Reputation: 392
Try this, this will work for you,
$str = "GOOD MORNING";
preg_replace("/\b([A-Z]{2,}(\s[A-Z]{2,})?)\b/", "<b>$1:</b>", $str);
Upvotes: 0