Homunculus Reticulli Homunculus Reticulli - 1 year ago 60
PHP Question

PHP: How to match all occurences of a regex pattern in a document

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:


$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;

Answer Source
  • You're missing a $
  • In your case you can simply return $out[0]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download