简体   繁体   English

忽略preg_match_all输出中的字符

[英]Ignore characters in preg_match_all output

I have this regex: 我有这个正则表达式:

preg_match_all('/{.*?}/', $html, $matches);

Which returns all strings that are written inside curly braces. 返回所有写在花括号内的字符串。 The $matches variable contains the { and } characters also. $ matches变量也包含{和}字符。 How can I remove them? 我该如何删除它们?

I don't want to do: 我不想这样做:

if ($matches[0] == "{variable}")

And I don't want to add ( and ) characters to the regexp because I don't want to use: 而且我不想在正则表达式中添加(和)字符,因为我不想使用:

preg_match_all('/{(.*?)}/', $html, $matches);
if ($matches[0][0] == "variable")

So is there a simpler way to remove the curly braces from the $matches within the regex? 那么是否有更简单的方法从正则表达式中的$ matches中删除花括号?

In PCRE (PHP's implementation of regex), you can use lookarounds to do zero-length assertions. 在PCRE(PHP的regex实现)中,您可以使用lookarounds来执行零长度断言。 A lookbehind, (?<=...) , will make sure that expression occurs behind the internal pointer. lookbehind (?<=...)将确保表达式出现在内部指针后面。 A lookahead, (?=...) , will make sure that expression occurs ahead of the internal pointer. 前瞻(?=...)将确保表达式发生在内部指针之前。 These can both be negated if need be: (?<!...) or (?!...) . 如果需要,这些都可以被否定: (?<!...)(?!...)


This brings us to this expression: 这给我们带来了这样的表达:

(?<={).*?(?=})

Demo 演示


Implement it the same way: 以同样的方式实现它:

preg_match_all('/(?<={).*?(?=})/', $html, $matches);
// $matches[0] = 'variable';

@CasimirEtHippolyte makes a good point. @CasimirEtHippolyte提出了一个很好的观点。 This is a great example of where a lazy dot-match-all is not necessary and will potentially decrease performance with backtracking. 这是一个很好的例子,说明了懒惰的点匹配 - 所有这些都不是必需的,并且可能会通过回溯来降低性能。 You can replace the .*? 你可以替换.*? with [^}]* to match 0+ non- } characters. 使用[^}]*匹配0+非}字符。

Or reset after the { and match characters, that are not } . 或者在{和匹配字符之后重置 } ,而不是} If {} are balanced, don't need another } 如果{}是平衡的,则不需要另一个}

{\K[^}]*

See example on regex101 请参阅regex101上的示例

(?<={).*?(?=})

用这个替换你的正则表达式。这样可行。

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

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