PHP 有一个preg_split 函数来处理这类事情。 preg_split 允许您通过可以定义为正则表达式模式的分隔符拆分字符串。此外,它还有一个参数允许您在匹配/拆分结果中包含匹配的分隔符。
因此,不是编写正则表达式来匹配全文,而是正则表达式用于分隔符本身。
示例:
$string = "This is a t3xt with special characters like !#. *AND and this is another text with special characters *AND this repeats *OR do not repeat *OR have more strings *AND finish with this string.";
$string = preg_split('~(\*(?:AND|OR))~',$string,0,PREG_SPLIT_DELIM_CAPTURE);
print_r($string);
输出:
Array
(
[0] => This is a t3xt with special characters like !#.
[1] => *AND
[2] => and this is another text with special characters
[3] => *AND
[4] => this repeats
[5] => *OR
[6] => do not repeat
[7] => *OR
[8] => have more strings
[9] => *AND
[10] => finish with this string.
)
但如果您真的想坚持使用preg_match,则需要使用preg_match_all,它类似于preg_match(您在问题中标记的内容),除了它会进行全局/重复匹配.
示例:
$string = "This is a t3xt with special characters like !#. *AND and this is another text with special characters *AND this repeats *OR do not repeat *OR have more strings *AND finish with this string.";
preg_match_all('~(?:(?:(?!\*(?:AND|OR)).)+)|(?:\*(?:AND|OR))~',$string,$matches);
print_r($matches);
输出:
Array
(
[0] => Array
(
[0] => This is a t3xt with special characters like !#.
[1] => *AND
[2] => and this is another text with special characters
[3] => *AND
[4] => this repeats
[5] => *OR
[6] => do not repeat
[7] => *OR
[8] => have more strings
[9] => *AND
[10] => finish with this string.
)
)
首先,请注意,与preg_split 不同,preg_match_all(和preg_match)返回多维度数组,而不是单维度数组。其次,从技术上讲,我使用的模式可以简化一点,但代价是必须在返回的多维数组中引用多个数组(一个数组用于匹配的文本,另一个数组用于匹配的分隔符) ,然后您将不得不循环并替换参考; IOW 将进行额外的清理以获得具有两个匹配集的最终单个数组,如上所述。
我只展示这种方法是因为您在技术上要求在您的问题中使用它,但我建议使用preg_split,因为它消除了很多这种开销,以及为什么首先创建它(以更好地解决方案像这样)。