Eddie D.
Eddie D.

Reputation: 145

how should I do to match uppercase words also containing colon

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

Answers (4)

Expedito
Expedito

Reputation: 7795

preg_replace("/([A-Z]{2,}\s[A-Z]{2,}:?)/", "<b>$1</b>", $str);

Output:

<b>GOOD MORNING:</b>

Upvotes: 0

Ahmed Masud
Ahmed Masud

Reputation: 22382

There are a few different ways:

Any of the following should suffice:

  1. preg_replace("/([A-Z:]{2,}(\s[A-Z:]{2,})?)/", "<b>$1</b>", $str);
  2. preg_replace("/([A-Z]{2,}(\s[A-Z:]{2,})?)/", "<b>$1</b>", $str);
  3. 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

Casimir et Hippolyte
Casimir et Hippolyte

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

K P
K P

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

Related Questions