开发者

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

开发者 https://www.devze.com 2023-01-22 10:34 出处:网络
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.

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);


Close:

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


I believe there is a PHP package for rendering Markdown. Rather than rolling your own, try using an existing set of code that's been written and tested.


Mmm I guess this could work

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

You find all sequences **something** and then you substitute the entire sequence found with the bold tag and inside it (the $1) the first captured group (the brackets in the expression).


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号