php - regex: select all characters before and after a specific string
问题描述
I want to select all text before and after a specific substring, I used the following expression to do that, but it not selecting all the needed text:
/^(?:(?!\<\?php echo[\s?](.*?)\;[\s?]\?\>).)*/
for example:
$re = '/^(?:(?!\<\?php echo[\s?](.*?)\;[\s?]\?\>).)*/';
$str = 'customFields[<?php echo $field["id"]; ?>][type]';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
it will select only this part customFields[
, while the expected result should be customFields[
and ][type]
解决方案
The pattern ^(?:(?!\<\?php echo[\s?](.*?)\;[\s?]\?\>).)*
uses a tempered greedy token which matches any character except a newline from the start of the string ^
that fulfills the assertion of the negative lookahead.
That will only match customFields[
For your example data you could make use of a tempered greedy token regex demo, but instead you could also just make use of a negated character class and SKIP FAIL:
^[^[]+\[|<\?php echo\s(.*?)\;\s\?\>(*SKIP)(*FAIL)|\]\[[^]]*\]
For example
$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);
Result
Array
(
[0] => Array
(
[0] => customFields[
)
[1] => Array
(
[0] => ][type]
)
)
To get a more exact match you might also use capturing groups:
^((?:(?!<\?php echo[\s?](?:.*?)\;\s\?>).)*)<\?php echo\s(?:.*?)\;[\s?]\?>(.*)$
推荐阅读
- javascript - Html CSS form not showing radio button
- python-3.7 - Python“序列化”未定义
- java - 不显示图像jframe
- swift - 如何从 Swift 中的段落开始到 UITextView
- reactjs - 如何从服务器向 socket.io 客户端发送 cookie?
- python - 减去pandas中的一批列
- javascript - 如何格式化来自后端的日期字符串?
- mysql - sql语句从另一个表中选择所有
- python - Python:如何在打印函数中添加带有变量的新行
- c# - TripleDES Decryptor 在第一次调用 TransformBlock 时什么也不做