miami
miami

Reputation: 49

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.

Upvotes: 1

Views: 549

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626929

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.

Upvotes: 1

Related Questions