我如何在这种情况下使用preg_replace模式?

时间:2014-07-01 13:49:37

标签: php preg-replace preg-match

你可以帮我解决我的问题的perg_replace模式吗? 我想从preg_replace创建粗体和斜体文本,文本粗体的单词用**bold**包围,文本斜体用##italic##包围。

实施例

$before = "Focus on the **user** and all else will ##follow##.";
$after = preg_replace($patterns, $replace, $before);

我想要这样的结果,它的模式和替换模式应该是什么?谢谢大家。

$after = "Focus on the <b>user</b> and all else will <em>follow</em>.";

1 个答案:

答案 0 :(得分:1)

以下内容应该足够了:

function format_text($string) {
    $string = preg_replace('/(\*\*(.*?)\*\*)/', '<b>\\2</b>', $string);
    $string = preg_replace('/(##(.*?)##)/', '<em>\\2</em>', $string);
    return $string;
}

请注意(.*?)中的问号,因为我们不希望所谓的贪婪匹配.*会尝试匹配尽可能多的文本,但我们希望将匹配限制为**或##中的“最小”可能文本。