Question

I am doing some data munging on documents which may (or may not - as the case may be) have ocurrence(s) of a regular expression pattern in their content.

I would like to write a PHP function to use to process the documents - the job of the function is to return an array of all matching patterns sound in the document (if they exist), or to return an empty array if no matches were found.

I am sure that this involves using the PHP function preg_match_all, however, I do not understand the format of the array returned by preg_match_all. I simply want to return a 1 dimensional (i.e. non-nested array) of the strings that match as follows:

<?php 

   $pattern = "^[h].[a-z]{3,4}";
   $doc = file_get_contents('some_pathname');

   function get_matching_patterns($pattern, $doc){
     $out = array();

     if (strlen($doc) && strlen($pattern)){
        // not sure about this - I don't like the complicated nested array returned
        // by preg_match-all
        preg_match_all($pattern, $doc, $out); 
     }

     return out;
   }
?>
Was it helpful?

Solution

  • You're missing a $
  • In your case you can simply return $out[0]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top