正则表达式,当有2个字符相同时不替换?

时间:2013-02-23 20:23:29

标签: php regex

我需要能够将*hello*替换为somethinghellosomething。我可以使用正则表达式#\*(.*?)\*#执行此操作。问题是,我想忽略任何**hello**。我尝试了#\*([^\s].*?)\*#,但它有效,但返回*somethinghellosomething*,而不只是**hello**。我需要在表达式中添加什么,以确保它不会替换任何**包含的字符串?

3 个答案:

答案 0 :(得分:4)

您可以尝试lookaround assertions仅在不在其他*之前或之后进行匹配。

(?<!\*)\*([^*]+)\*(?!\*)

另请注意,我已将您的.*?更改为[^*]+。否则,它可以匹配两个连续的星号,因为.*?可以匹配 nothing

示例:http://regexr.com?33sp0


一块一块,这是:

(?<!\*)    # not preceded by an asterisk
\*         # an asterisk
([^*]+)    # at least one non-asterisk character
\*         # an asterisk
(?!\*)     # not followed by an asterisk

答案 1 :(得分:0)

试试这个

 #(\*+)(.*?)(\*+)#

示例代码

 $notecomments=" **hello**  *hello*   ***hello*** ****hello**** ";
 $output=preg_replace_callback(array("#(\*+)(.*?)(\*+)#"),function($matches){
if($matches[1]=="*")
  return 'something'.$matches[2].'something';
else
  return $matches[0];

},' '.$notecomments.' ');

输出:

  **hello** somethinghellosomething ***hello*** ****hello****

答案 2 :(得分:0)

$text = '**something**   **another**  *hello*';
function myfunc($matches)
{
 if($matches[0][0] == '*' && $matches[0][1] == '*'){
  return $matches[0];
 }else{
  return str_replace('*', 'something', $matches[0]);
 }
}
echo preg_replace_callback("/(\*){1,2}([^*]+)(\*){1,2}/","myfunc", $text);