5

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);
Entity
  • 7,972
  • 21
  • 79
  • 122
  • 2
    It might be possible to do exactly what you asked in regular expressions but keep in mind that something like markdown shouldn't really be implemented using regular expressions. Joel Spolsky talks about this in one of the Stack Overflow podcasts. Look into finite state machines. – emurano Oct 25 '10 at 21:56
  • A link to the podcast: http://itc.conversationsnetwork.org/shows/detail4359.html – Jim Oct 25 '10 at 22:02
  • @emurano Languages that can be handled by FSM's are regular; thus they can be handled by regexes. – NullUserException Oct 25 '10 at 22:27
  • I guess since regexes basically generate FSMs on the fly then my argument is invalid :) – emurano Oct 25 '10 at 22:30

4 Answers4

9

Close:

$input = "Hello **bold** world";
$output = preg_replace("/\*\*(.*?)\*\*/", "<b>$1</b>", $input);
thetaiko
  • 7,816
  • 2
  • 33
  • 49
2

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.

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
1

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

Minkiele
  • 1,260
  • 2
  • 19
  • 32
0
$output = preg_replace("/\*\*(.*?)\*\*/", "<b>$1</b>", $input);
Steve Claridge
  • 10,650
  • 8
  • 33
  • 35