在其他文本中使用preg_replace()作为后缀和后缀

I've been trying to make a mini markup parser similar to Markdown in PHP. The input looks like this:

Some text **that is bold!** and some other text

into

Some text <b>that is bold!</b> and some other text

I've found countless resources on how to replace a chunk of text with another, but only one that actually replaces suffix and postfix: this answer. After messing around with it a bit it looks like this:

$s=preg_quote("**");

$in = preg_replace(
    array('%'.$s.'-%', '%-%', '%'.$s.'%'), 
    array('<b>','_','</b>'),
    $in);

Earlier attempts are equally clumsy. It's obvious I don't really get regex or that engine's syntax so I'm at a loss. The alternative is to hack the string into pieces and add/remove what I need, but regex seems much more elegant. Any ideas?


Fix: Earlier I wrote $s=preg_quote($s) by mistake, corrected to $s=preg_quote("**")

You should use a basic '\*\*(.+?)\*\*' regex.

$s = preg_replace(
    '/\*\*(.+?)\*\*/isU',
    '<b>$1</b>',
    $s);

I am not familiar with php pre_replace and its way to accept arrays like you show in your code. But generally speaking a regex approach to this would look like this:

Search for \*\*(.*?)\*\* and replace with <b>\1</b>. Let me explain this:

We are looking for a string in the form **any text here** the * need to be escaped because they have a special meaning in regex - hence the \*. The central part of the regex (.*?) is matching any string (. matches any character) of arbitrary length (* here has its regex meaning). But we only want to look for the next ** (there might be more later in the string) so we have to search ungreedy (hence the ?). The brackets makes the regex engine capture whatever is matched by this part of the regex.

Finally we reference the matched part by using \1 (also $1 is possible in some engines).

Try this

$string = explode('**', $sometext);
$newstr = '';
$size = count($string);
for ($i = 0; $i < $size; ++$i)  {
    if (($i % 2 == 0 || $i == 0 )&& $i != $size-1 )
        $newstr .= $string[$i]."<b>";
    else if($i % 2 != 0 && $i != $size && $i != $size-1 )
        $newstr .= $string[$i]."</b>" ;
    else if($i == $size-1)
        $newstr .= $string[$i];
}

echo $newstr;

Demo