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.
CodePudding user response:
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);
CodePudding user response:
Try the following and see if it meets your requirements:
$description = preg_replace(
'~(?:[[:alnum:]] )(?:_[[:alnum:]] ) ~',
'<b>$0</b>',
$description
);
Explanation:
~
delimiter(?:
start of non-capturing group[
start character class[:alnum:]
match alphanumeric characters
]
end character class
)
end non-capturing group(?:
start of non-capturing group_
match underscore[
start character class[:alnum:]
match alphanumeric characters
]
end character class
)
end non-capturing group
~
delimiter