doschni
doschni

Reputation: 43

Make part of a string bold with Regex and PHP

My problem is, that I need a part of a string bold. In my case 6000 Luzern. It's the zip-code and the town-name.

<?php
$pattern = '/[0-9]{4}.*(?=,)/';
$replacement = '<strong>'.$pattern.'</strong>';
$subject = 'Hello 6000 Luzern, 0586464129';
echo preg_replace($pattern , $replacement , $subject);
?>

Result: Hallo /[0-9]{4}.*(?=,)/, 5564641

The code is realising, what part I need, but how can it bold it? It should be like this:

Hello 6000 Luzern, 5564641

Upvotes: 1

Views: 1181

Answers (1)

anubhava
anubhava

Reputation: 785761

You can use your regex as:

$pattern = '/\b[0-9]{4}[^,]+\b/';

and replacement with $0 (matched string):

$replacement = '<strong>$0</strong>';

as you need to use matched back-reference in the replacement as well.

Now code:

echo preg_replace($pattern , $replacement , $subject);
//=> Hello <strong>6000 Luzern</strong>, <strong>0586464129</strong>

Regex \b[0-9]{4}[^,]+\b matches:

\b       # word boundary
[0-9]{4} # 4 digits
[^,]+    # 1 or more of non-comma chars
\b       # word boundary

Upvotes: 1

Related Questions