phpregexpreg-replace

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.


Solution

  • $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.