Victor Bjelkholm
Victor Bjelkholm

Reputation: 2216

Wrap <b> tags around substrings matching a regular expression

I'm using preg_match() for the first time but I'm stuck even before I got some code.

With the help from RegExr I have figured out that I need to use this expression:

/\(.*M\)\s.*?:/gm

What I need help with is how I gonna use this to place<b></b>around the matched text.

Upvotes: 0

Views: 442

Answers (2)

Alan Moore
Alan Moore

Reputation: 75222

$output = preg_replace('%\(.*M\)\s.*?:%', '<b>$0</b>', $input);

If you're working in PHP, you'd be better off using this online tester:

http://www.spaweditor.com/scripts/regex/

RegExr is a Flex app; the regex engine is the same, but the code used to invoke it is very different. For example (as Matthew pointed out), there's no g flag; you would use the preg_match_all method instead. Remember to add regex delimiters (I used %); I'm always forgetting those.

Upvotes: 1

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

preg_match('/\(.*M\)\s.*?:/', $input, $matches);
$output = "<b>$matches[0]</b>";

There is no g flag in PCRE, and I don't think you need multiline, because you're not using ^ or $.

Upvotes: 1

Related Questions