Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace markdown to HTML tags in PHP

I’m trying to grab the content between two sets of double underscores, and replace it between two underline html tags, but my regex is not quite right.

str = "**test**";
str = str_replace(/**(\wd+)**/g, "<b>$1<\/b>", $str);
// Should echo <b>test</b>

What I’m missing here ?

Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to bear in mind that:

  • str_replace does not use regex, you need preg_replace
  • /**(\wd+)**/g is rather a wrong pattern to use in PHP preg_* functions as the g flag is not supported. More, \wd+ matches a word char and then one or more d chars, you must have tried to match any alphanumeric chars. (\w+) is enough to use here. * are special regex metacharacters and need escaping.

So you need to use

<?php

$str = "**test**";
$str = preg_replace('/\*\*(\w+)\*\*/', '<b>$1</b>', $str);
echo $str;

See the PHP demo.

To match any text between double asterisks, you need

$str = preg_replace('/\*\*(.*?)\*\*/s', '<b>$1</b>', $str);

The s flag will make . also match line break characters.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading