Dest Dest - 2 years ago 147
PHP Question

preg_match_all multiple pattern leaves empty array values

I am trying to understand

with multiple patterns inside it, so I created html string variable and pattern.

Everything like trimming works fine but it outputs some array keys with empty values because of multiple pattern. If you know why it makes like this please tell me and also show me how it must be fixed.

My Code:

$cource = "<div><a href='test1'> <img src=\"test2\" /> <img src='test3' > <script src='test4'> <link href='test5'> </div>";

preg_match_all('/src=["\']([^"\']+)|href=\'([^\']+)/',$cource, $result);



enter image description here

Answer Source

You are getting empty values cause of using two capturing groups,

  • 1st is for src
  • 2nd is for href

hence you are getting empty values as per your data as first element has attribute href you got src blank (as it doesn't have it) so on and so forth.

You can grab results in one capture (second) group, first one is left for references for what attributes it's taken from.

$cource = "<div><a href='test1'>  <img src=\"test2\" /> <img src='test3' > <script src='test4'> <link href='test5'> </div>";

preg_match_all('/(href|src)=["\']([^"\']+)/',$cource, $result); 

In case you don't need reference attributes, you can use non capturing group ?:

preg_match_all('/(?:href|src)=["\']([^"\']+)/',$cource, $result); 

In Action:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download