David Smith
David Smith

Reputation: 511

PHP - Regular Expressions - Match regexp without including the same regexp multiple times

Using PHP, I have the folloowing code:

$text = '[text 1] highlight("ABC DEF") [text 2] highlight("GHI JKL") [text 3] [text 4]';

Then I want to catch the following groups:

group 1: highlight("ABC DEF") [text 2]
group 2: highlight("GHI JKL") [text 3] [text 4]

I tried the following:

preg_match_all('/highlight.*/', $text, $matches);
print_r($matches);

but I get:

Array
(
    [0] => Array
        (
            [0] => highlight("ABC DEF") [text 2] highlight("GHI JKL") [text 3] [text 4]
        )

)

But that's not what I want because it is all together.

I also tried:

preg_match_all('/highlight/', $text, $matches);
print_r($matches);

but I get:

Array
(
    [0] => Array
        (
            [0] => highlight
            [1] => highlight
        )

)

And that's not what I want neither.

Any idea what regexp to use in order to get the groups I mentioned above?

Upvotes: 1

Views: 71

Answers (2)

Andreas
Andreas

Reputation: 23968

Preg_split?

preg_split("/(highlight)/", $input_line);

Try it here: http://www.phpliveregex.com/p/hYr

With PREG_SPLIT_DELIM_CAPTURE option it will keep highlight in the string

Upvotes: 0

xate
xate

Reputation: 6379

<?php
$matches = array();

preg_match_all("/highlight\([^)]*\) .*?(?= highlight|$)/", '[text 1] highlight("ABC DEF") [text 2] highlight("GHI JKL") [text 3] [text 4]', $matches);

var_dump($matches);

For explanations:

https://regex101.com/r/8ZQjNr/5

Upvotes: 3

Related Questions