I want to take all of the characters from line with the regexp.
$str = "html code <script> var='a,b,c,d,e,f,g,h' </sript> html code";
preg_match_all ('#var =.((\w),?)+.#',$str,$m);
echo "<pre>";
print_r ($ m);
echo "</ pre>";
result:
Array
(
[0] => Array
(
[0] => var = 'a, b, c, d, e, f, g, h'
)
[1] => Array
(
[0] => h
)
[2] => Array
(
[0] => h
)
)
h - last search symbol, why?
Because you reuse the group multiple times with the +
after the group. This way, the group is matched every time until the h
, where it matches one last time, and the expression is done.
If you want every match to be in a single group, you'll either have to afterwards split your complete match or create every group for itself.
I think you are trying to do something that is not perfectly suited to regular expressions - which although sometimes are the best tool for a job, they are limited to matching patterns that can be described in a certain way. They have no control logic, so can not loop or recurse. It is good to use regex along with other methods to achieve what you want.
In this case, I would use regex (preg_match - not preg_match_all) to match var='...'
so you can extract the ...
and then split the string by comma, separating each item into an array.
If you try to bend regex to do it all in one operation, it ends up being much less efficient, and less reliable (as it is hard to write rock solid regex for these kind of situations).