Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 532
Entity Avatar asked Oct 25 '10 21:10

Entity


People also ask

What does Preg_replace do in PHP?

The preg_replace() function returns a string or array of strings where all matches of a pattern or list of patterns found in the input are replaced with substrings. There are three different ways to use this function: 1. One pattern and a replacement string.

What is the difference between Str_replace and Preg_replace?

str_replace replaces a specific occurrence of a string, for instance "foo" will only match and replace that: "foo". preg_replace will do regular expression matching, for instance "/f. {2}/" will match and replace "foo", but also "fey", "fir", "fox", "f12", etc.

What does (? I do in regex?

(? i) makes the regex case insensitive. (? c) makes the regex case sensitive.

How do you replace words in regex?

Word supports find/replace with it own variation of regular expressions (regex), which is called wildcards. To use regex: Ctrl-H (Find/Replace) ⇒ Check "Use wildcards" option under "More".


2 Answers

Close:

$input = "Hello **bold** world";
$output = preg_replace("/\*\*(.*?)\*\*/", "<b>$1</b>", $input);
like image 74
thetaiko Avatar answered Sep 26 '22 02:09

thetaiko


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.

like image 23
Andy Lester Avatar answered Sep 24 '22 02:09

Andy Lester