PHP-捕获正则表达式匹配项以及不匹配的余数
对于像PHP-捕获正则表达式匹配项以及不匹配的余数,php,regex,Php,Regex,对于像asdftheremainderhere这样的字符串,使用正则表达式匹配asdf将字符串拆分为asdf和theremainderhere 我尝试使用: preg_match('/asdf|ghik/', 'asdftheremainderhere', $matches);` 但是只有asdf是$matches数组中$matches的唯一元素$matches[0]将是完整模式匹配,$matches[1]将是第一个捕获组(asdf | ghik),$matches[2]将是第二个捕获组(.*
asdftheremainderhere
这样的字符串,使用正则表达式匹配asdf
将字符串拆分为asdf
和theremainderhere
我尝试使用:
preg_match('/asdf|ghik/', 'asdftheremainderhere', $matches);`
但是只有
asdf
是$matches
数组中$matches
的唯一元素$matches[0]
将是完整模式匹配,$matches[1]
将是第一个捕获组(asdf | ghik)
,$matches[2]
将是第二个捕获组(.*)
任何字符的0次或更多次:
preg_match('/(asdf|ghik)(.*)/', 'asdftheremainderhere', $matches);
print_r($matches);
收益率:
Array
(
[0] => asdftheremainderhere
[1] => asdf
[2] => theremainderhere
)
在
$matches
数组中,$matches[0]
将是完整模式匹配,$matches[1]
将是第一个捕获组(asdf|ghik)
,$matches[2]
将是第二个捕获组(.*)
,它是任何字符0次或多次:
preg_match('/(asdf|ghik)(.*)/', 'asdftheremainderhere', $matches);
print_r($matches);
收益率:
Array
(
[0] => asdftheremainderhere
[1] => asdf
[2] => theremainderhere
)
您可以使用捕获组来执行类似的操作,不是吗
preg_match('/(asdf)(.*)/', 'asdftheremainderhere', $matches);
如果您希望换行并希望在剩余部分中使用换行符,请添加多行标志。您可以使用捕获组来执行类似操作,不是吗
preg_match('/(asdf)(.*)/', 'asdftheremainderhere', $matches);
如果希望换行并希望在剩余部分中使用换行符,请添加多行标志。您可以将preg\u split与保存分隔符的
\K
一起使用
print_r(preg_split('/(asdf|ghik)\K/', 'asdftheremainderhere'));
结果
Array
(
[0] => asdf
[1] => theremainderhere
)
您可以将preg_split与保存分隔符的
\K
一起使用
print_r(preg_split('/(asdf|ghik)\K/', 'asdftheremainderhere'));
结果
Array
(
[0] => asdf
[1] => theremainderhere
)
您需要
preg\u split
,在asdf
周围有一个捕获组。如何捕获捕获组<代码>$matches=preg_split(“/(asdf)|(ghik)/”,$string)您可以使用'(asdf | ghik)
。显然preg_split
是一种方法,但是使用preg_split_DELIM_CAPTURE
(请参阅php手册)选项和模式:/(asdf | ghik)/
。然后,如果您只想轻松地找到分隔符,那么很简单,它都是奇数项(其他部分为偶数项)。如果在“asdf”之前有任何内容,您接受的解决方案将失败。您需要在asdf
周围有一个捕获组进行preg\u split
。如何捕获捕获组<代码>$matches=preg_split(“/(asdf)|(ghik)/”,$string)您可以使用'(asdf | ghik)
。显然preg_split
是一种方法,但是使用preg_split_DELIM_CAPTURE
(请参阅php手册)选项和模式:/(asdf | ghik)/
。然后,如果您只想轻松地找到分隔符,那么很简单,它都是奇数项(其他部分为偶数项)。如果在“asdf”之前有任何内容,您接受的解决方案将失败。