我想选择特定子字符串之前和之后的所有文本,我使用以下表达式来做到这一点,但它没有选择所有需要的文本:/^(?:(?!\<\?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]
2 回答
![?](http://img1.sycdn.imooc.com/545847d40001cbef02200220-100-100.jpg)
小怪兽爱吃肉
TA贡献1852条经验 获得超1个赞
该模式^(?:(?!\<\?php echo[\s?](.*?)\;[\s?]\?\>).)*
使用经过调节的贪婪令牌,该令牌匹配从字符串开始处的新字符(除了^
满足否定超前断言的字符串开始)之外的所有字符。
那只会匹配 customFields[
对于您的示例数据,您可以使用经过改进的贪婪令牌regex演示,但也可以仅使用否定的字符类和SKIP FAIL:
^[^[]+\[|<\?php echo\s(.*?)\;\s\?\>(*SKIP)(*FAIL)|\]\[[^]]*\]
例如
$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?]\?>(.*)$
- 2 回答
- 0 关注
- 1922 浏览
添加回答
举报
0/150
提交
取消