preg_replace - how to match anything that's NOT \*\*
I can't seem to figure out the regular expression to match any string that's in the format
**(anything that's not **)**
I tried doing this in php
$str = "** hello world * hello **";
$str = preg_replace('/\*\*(([^开发者_JAVA百科\*][^\*]+))\*\*/s','<strong>$1</strong>',$str);
but no string replacement was done.
You can use an assertion ?!
paired with a character-wise .
placeholder:
= preg_replace('/\*\*(((?!\*\*).)+)\*\*/s',
This basically means to match any number of anythings (.)+
, but the .
can never occupy the place of a \*\*
You could use lazy match
\*\*(.+?)\*\*
# "find the shortest string between ** and **
or a greedy one
\*\*((?:[^*]|\*[^*])+)\*\*
# "find the string between ** and **,
# comprising of only non-*, or a * followed by a non-*"
This should work:
$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 );
Try with:
$str = "** hello world * hello **";
$str = preg_replace('/\*\*(.*)\*\*/s','<strong>$1</strong>',$str);
精彩评论