Dest Dest - 6 months ago 17
PHP Question

preg_match_all multiple pattern leaves empty array values

I am trying to understand

preg_match_all
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:

<?php
$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);

var_dump($result);
?>


Output:

enter image description here

Answer

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: https://eval.in/580585

Comments