Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/261.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP-捕获正则表达式匹配项以及不匹配的余数_Php_Regex - Fatal编程技术网

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”之前有任何内容,您接受的解决方案将失败。