我似乎无法找出正则表达式匹配的格式的任何字符串的preg_replace - 如何匹配任何非 * *
**(anything that's not **)**
我试图在PHP这样做
$str = "** hello world * hello **";
$str = preg_replace('/\*\*(([^\*][^\*]+))\*\*/s','<strong>$1</strong>',$str);
但没有字符串替换完成。
我似乎无法找出正则表达式匹配的格式的任何字符串的preg_replace - 如何匹配任何非 * *
**(anything that's not **)**
我试图在PHP这样做
$str = "** hello world * hello **";
$str = preg_replace('/\*\*(([^\*][^\*]+))\*\*/s','<strong>$1</strong>',$str);
但没有字符串替换完成。
您可以使用assertion?!
一个字符明智配对.
占位符:
= preg_replace('/\*\*(((?!\*\*).)+)\*\*/s',
这基本上意味着匹配任意数量的anythings (.)+
,但.
永远不能占据的\*\*
你可以用懒惰匹配
\*\*(.+?)\*\*
# "find the shortest string between ** and **
或贪婪的一个
\*\*((?:[^*]|\*[^*])+)\*\*
# "find the string between ** and **,
# comprising of only non-*, or a * followed by a non-*"
这应该工作:
$result = preg_replace(
'/\*\* # Match **
( # Match and capture...
(?: # the following...
(?!\*\*) # (unless there is a ** right ahead)
. # any character
)* # zero or more times
) # End of capturing group
\*\* # Match **
/sx',
'<strong>\1</strong>', $subject);
preg_replace('/\*\*(.*?)\*\*/', '<strong>$1</strong>', $str);
的地方尝试使用:
$str = "** hello world * hello **";
$str = preg_replace('/\*\*(.*)\*\*/s','<strong>$1</strong>',$str);
'。*'也会快乐地匹配'**'。 – 2011-05-29 19:47:07
是的,但不是最后一个 - 我认为这是他需要的 – 2011-05-29 19:54:39
考虑** **这很重要**这不重要**但这是**' - 您的正则表达式将匹配整个字符串,而不是只有“重要”位。 – 2011-05-30 07:42:15
+1非常好的一个 – dariush 2014-06-12 20:50:53