doujie7886 2016-09-13 19:27
浏览 111
已采纳

PHP PCRE匹配标点但不是++

I tried to search for an answer to this for a while but could not find it. There were many posts related to matching text which is not preceeded by certain text but none seems to work for this case where + is matched but it is allowed only when preceeded by a single + (eg. ++)

I am trying to remove punctuation marks from text but let two consecutive ++ signs to stay but single + signs to disappear

$text="Hello World! C+ C++ C#";
print_r(preg_replace('/(?!\+\+)[[:punct:]]/', ' ', $text));

Results in (I am not sure why the latter + is removed? can somebody explain?):

Hello World C C+ C

If I try:

$text="Hello World! C+ C++ C#";
print_r(preg_replace('/(?!\+)[[:punct:]]/', ' ', $text));

Result is:

Hello World C+ C++ C

But the result I want is:

Hello World C C++ C

Thanks

UPDATE: I realized that I should probably mention that I will have other characters which I want to avoid. I may have oversimplified the question. For example I may want to avoid # also thus result would be

Hello World C C++ C#

the solution should be easily expandable. I am sorry about the inconvenience caused by this missing information.

  • 写回答

4条回答 默认 最新

  • dongzhanyan3667 2016-09-13 19:31
    关注

    You have a couple of choices here, one being:

    (?<!\+)[+#](?!\+)
    # with lookarounds making sure no + is after/behind
    

    See a demo on regex101.com.


    In PHP:
    <?php
    
    $regex = '~(?<!\+)[+#](?!\+)~';
    
    $string = 'Hello World! C+ C++ C#';
    $string = preg_replace($regex, '', $string);
    
    echo $string;
    ?>
    


    Another one would be to use the (*SKIP)(*FAIL) mechanism (which is a bit faster in this example):
    \+{2}(*SKIP)(*FAIL)|[+#]
    # let two consecutive ++ always fail
    

    See a demo for this one on regex101.com as well.

    Last but not least: If you want to add characters/expressions that should be avoided as well, you can put them in a non-capturing group and let this one fail:

    (?:\#|\+{2})(*SKIP)(*FAIL)|
    [[:punct:]]
    

    Yet another demo on the wonderful regex101.com site.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改