php, simple preg_match_all example not working

370 views Asked by At

It seems like the preg_match is working until it finds the first match and then stops:

$bgStr="<><><><><><><>";


$regStr='/</';

preg_match_all($regStr,$bgStr,$matches);

echo count($matches);

gives me the result of: "1". What am I missing?

1

There are 1 answers

1
mickmackusa On

There are at least 3 logical ways to achieve your count on the less than symbol. The last one listed being the best / most efficient / recommended one...

preg_match_all() is overkill. It creates an array in an array containing elements which must be counted.

$bgStr="<><><><><><><>";
if(preg_match_all('/</',$bgStr,$matches)){
    echo sizeof($matches[0]);  // counts the fullstring elements that preg_match_all creates
}

count_chars() is overkill. It creates an array of elements like CodeNumber=>Count for each character found in the string.

$bgStr="<><><><><><><>";
echo count_chars($bgStr,1)[60];

substr_count() is the leanest method and was specifically designed for this purpose. This is a single-function, one-liner that does not generate excess data nor requires additional variables.

$bgStr="<><><><><><><>";
echo substr_count($bgStr,'<');

All methods above will output: 7