phpreplacemarkdown

Replace pairs of double-asterisks with opening and closing <strong> tags


When I replace something, it will just replace everything; That's okay. But what I would like to know is this:

str_replace("*", "<strong>", $message);

Is it possible to use str_replace() for codes like * This content is Bold *, just having the content, but still replacing the asterisks with <strong> and </strong>?

Example:

Original: **This Should be Bold** After Replacing: <strong>This Should be Bold</strong>


Solution

  • Use regular expression instead; it's more convenient:

    $message = "**This Should be Bold**";
    $message = preg_replace('#\**([^\*]+)\**#m', '<strong>$1</strong>', $message);
    echo $message;
    

    Or if you want to limit the number of asteroids to 2:

    '#\*{1,2}([^\*]+)\*{1,2}#m'