Raphael Rafatpanah Raphael Rafatpanah - 5 months ago 10
PHP Question

PHP - Capture regex match as well as the non-matched remainder

For a string like

asdftheremainderhere
, what is a simple way to split the string to
asdf
and
theremainderhere
using a regex to match
asdf
?

I tried using:

preg_match('/asdf|ghik/', 'asdftheremainderhere', $matches);`


But only
asdf
is the only element of
$matches
.

Answer

In the $matches array $matches[0] will be the full pattern match, $matches[1] will be the first capture group (asdf|ghik) and $matches[2] will be the second capture group (.*) which is any character 0 or more times:

preg_match('/(asdf|ghik)(.*)/', 'asdftheremainderhere', $matches);

print_r($matches);

Yields:

Array
(
    [0] => asdftheremainderhere
    [1] => asdf
    [2] => theremainderhere
)
Comments