1

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?

2 Answers 2

3
<?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

Sign up to request clarification or add additional context in comments.

3 Comments

A faster equivalent of the same regex is highlight\([^)]*\)[^h]*(?:h(?!ighlight\([^)]*\))[^h]*)*.
@WiktorStribiżew Great job there!:)
In PCRE, lazy dot matching patterns are better unrolled. As a bonus, this will match across newlines, without the DOTALL modifier.
0

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

2 Comments

Doesn't provide the output he wants.
He has not showed what he wants, only what he wants to capute. If you make a regex with "highlight", you know what is missing. But sure, you can use the option PREG_SPLIT_DELIM_CAPTURE to keep the delimiter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.