繁体   English   中英

正则表达式:选择特定字符串前后的所有字符

[英]regex: select all characters before and after a specific string

我想选择特定子字符串前后的所有文本,我使用以下表达式来做到这一点,但它没有选择所有需要的文本:

/^(?:(?!\<\?php echo[\s?](.*?)\;[\s?]\?\>).)*/

例如:

$re = '/^(?:(?!\<\?php echo[\s?](.*?)\;[\s?]\?\>).)*/';
$str = 'customFields[<?php echo $field["id"]; ?>][type]';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

它只会选择这部分customFields[ ,而预期的结果应该是customFields[][type]

检查此链接以进行调试

模式^(?:(?!\\<\\?php echo[\\s?](.*?)\\;[\\s?]\\?\\>).)*使用一个温和的贪婪标记,它匹配除从字符串^开始的换行符,它满足负前瞻的断言。

那只会匹配customFields[

对于您的示例数据,您可以使用温和的贪婪令牌regex demo ,但您也可以只使用否定字符类SKIP FAIL

^[^[]+\[|<\?php echo\s(.*?)\;\s\?\>(*SKIP)(*FAIL)|\]\[[^]]*\]

正则表达式演示| php 演示

例如

$re = '/^[^[]+\[|<\?php echo\s(.*?)\;\s\?\>(*SKIP)(*FAIL)|\]\[[^]]*\]/';
$str = 'customFields[<?php echo $field["id"]; ?>][type]';
preg_match_all($re, $str, $matches, PREG_SET_ORDER);
print_r($matches);

结果

Array
(
    [0] => Array
        (
            [0] => customFields[
        )

    [1] => Array
        (
            [0] => ][type]
        )

)

要获得更精确的匹配,您还可以使用捕获组:

^((?:(?!<\?php echo[\s?](?:.*?)\;\s\?>).)*)<\?php echo\s(?:.*?)\;[\s?]\?>(.*)$

正则表达式演示| php 演示

使用positive lookarounds怎么样:

(.*)(?=\<\?php echo)|(?<=\?\>)(.*)

演示

暂无
暂无

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

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