Regex match and replace of IDs

Issue

I’m trying to do a match and replace of strings that follow these patterns:

text_text_text
text_text
text_123

Basically, alphanumeric and one or more underscores.

The replace will basically just take the match and add a bold tag to it.

I have this so far but it matches basically with most of the text in my content:

$description = preg_replace(
"~[[:alnum:]+_]+~",
"<b>\\0<\b>",
$description);

Any help is appreciated.

Solution

If you only want to match when there’s at least one underscore, you have to make that a required character, not part of the character set.

$description = preg_replace('~([[:alnum:]]+_)+[[:alnum:]]+~', '<b>$0</b>', $description);

Answered By – Barmar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published