Search code examples
phpregexpreg-replacenon-greedy

PHP preg_replace to turn **xyz** to <b>xyz</b>


I decided to, for fun, make something similar to markdown. With my small experiences with Regular Expressions in the past, I know how extremely powerful they are, so they will be what I need.

So, if I have this string:

    Hello **bold** world

How can I use preg_replace to convert that to:

    Hello <b>bold</b> world

I assume something like this?

    $input = "Hello **bold** world";
    $output = preg_replace("/(\*\*).*?(\*\*/)", "<b></b>", $input);

Solution

  • Close:

    $input = "Hello **bold** world";
    $output = preg_replace("/\*\*(.*?)\*\*/", "<b>$1</b>", $input);