phpreplace

How to replace specific characters with an element tag in PHP


I wanted to make a PHP function that would make text bold between double asterisks, and italic between one asterisk, (quite like the editor on Stack Overflow).

The same rules apply, if there's a space between the * and the word, it shouldn't render.

I tried, but I only came this far, as I don't know how to make the odd asterisks <b> and the even ones </b>:

$thenewtext = str_replace("**", "<b>", "**Hello World** of PHP");

Solution

  • A simple regex will do the trick:

    $thenewtext = preg_replace('#\*{2}(.*?)\*{2}#', '<b>$1</b>', '**Hello World** of PHP');