Regex matches a line between%

I am trying to combine substrings enclosed in%, but preg_match_allit seems to include several at the same time on the same line.

The code is as follows:

preg_match_all("/%.*%/", "%hey%_thereyou're_a%rockstar%\nyo%there%", $matches);
print_r($matches);

Which produces the following conclusion.

Array
(
    [0] => Array
        (
            [0] => %hey%_thereyou're_a%rockstar%
            [1] => %there%
        )

)

However, I would like it to create the following array:

[0] => %hey%
[1] => %rockstar%
[2] => %there%

What am I missing?

+3
source share
6 answers

Replace " ." in your regex with " [^%]":

preg_match_all("/%[^%]*%/", "%hey%_thereyou're_a%rockstar%\nyo%there%", $matches);

, , "." "" , , , % . "[^%]" , , , , .

"?" , " ":

preg_match_all("/%.*?%/", "%hey%_thereyou're_a%rockstar%\nyo%there%", $matches);

, , - , , , , .

+12

- ?, :

/%.*?%/

, s (DOTALL):

/%.*?%/s
+4

? *:

preg_match_all("/%.*?%/", "%hey%_thereyou're_a%rockstar%\nyo%there%", $matches);
+2

, . , . .*? .

+1

/%[^%]+%/ - , , .

, . /%.+%/U, ( ).

+1

|% (\ W +)% | , .

+1

Source: https://habr.com/ru/post/1715052/


All Articles