简体   繁体   English

用正则表达式求反

[英]Negate   with regex

Trying to negate   试图否定  string but nothing seems to work.. 字符串,但似乎无济于事。

Heres what im trying to do: 我正在尝试做以下事情:

Input: 输入:

example: word1 word2 

Output that i want: 我想要的输出:

example: **** word2

Current code: 当前代码:

preg_replace('/example: (\s|.nbsp;)?[^<\n\r (&nbsp;)]*', 'example: ****', $sContent);

From what i understand, [^<\\n\\r (&nbsp;)] needs to change. 据我了解, [^<\\n\\r (&nbsp;)]需要改变。 Currently it takes every symbol from &nbsp; 目前,它需要&nbsp;每个符号 separately, i want it to take the whole string. 分别,我希望它采取整个字符串。 How can i do that? 我怎样才能做到这一点?

You can simply use .*? 您可以简单地使用.*? to match everything before the &nbsp; 匹配&nbsp;之前的所有内容 and use capture groups to put back everything else: 并使用捕获组放回其他所有内容:

preg_replace('/(example: ).*?(&nbsp;)/', '$1****$2', $sContent);

regex101 demo regex101演示

Or you can use lookarounds to avoid capture groups... 或者您可以使用环顾四周来避免捕获组...

preg_replace('/(?<=example: ).*?(?=&nbsp;)/', '****', $sContent);

regex101 demo regex101演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM