Find the number of matches from a reg.ex

I have a question about how regular expressions and PHP may be able to count the number of successful matches and output it or only do something once a minimum number of matches are found.

I am aware of a way of limiting a regular expression using something like {2,5} but I cannot get that to work, so I suppose that my only option is to use some sort of if statement that counts the number of matches from the regular expression and then does something if that number meets or exceeds what I specify.

But how do I get that magic number?

Take a look at [fphp]preg_match_all[/fphp]. More specifically take a look at what it returns:

Returns the number of full pattern matches (which might be zero), or FALSE if an error occurred.

:slight_smile:

I’ve heard of that function and I’ve tried it before, but I couldn’t work out how to use it correctly. It just kept breaking my code.

Could you post the code you tried so we can have a look?

No, I didn’t keep it. I struggled with the extra parts that preg match has, and how to get the result out of it.

Okay. Allow me to give an example then:


$str = 'When we test this test it is testing whether the test is correct.';
if (preg_match_all('~test~', $str, $matches) > 3) {
   echo '"Test" occurs more that 3 times';
} else {
   echo '"Test" occurs 3 times or less';
}

:slight_smile:

Does this clear things up any?


<?php
preg_match_all('~[a-z]+~', 'abc12d3ef456g7', $matches);

var_dump(
  $matches
);

/*
  array(1) {
    [0]=>
    array(4) {
      [0]=>
      string(3) "abc"
      [1]=>
      string(1) "d"
      [2]=>
      string(2) "ef"
      [3]=>
      string(1) "g"
    }
  }
*/

ScallioXTX, thanks for that example. That has helped and I think that I’ll be able to use that for what I need.

AnthonySterling: your example is a bit beyond my level, but thanks for responding.