Partack
Partack

Reputation: 886

preg_match_all not doing what I'm expecting it to do?

This code seems pretty easy and logical to me, I must be tired because it's not doing what I expect it to..

//look for any letter, number or underscore    
$regexTags = "/[a-z0-9_]/i";

//needlessly large string..
$string = "111 222 333 444 555 666 777";
preg_match_all($regexTags, $string, $regexMatches);
print_r($regexMatches);

//$regexMatches spits out  [0] => Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 2 [5] => 2 [6] => 3 [7] => 3 [8] => 3 [9] => 4 [10] => 4 [11] => 4 [12] => 5 [13] => 5 [14] => 5 [15] => 6 [16] => 6 [17] => 6 [18] => 7 [19] => 7 [20] => 7))
//as expected.

//Count how many variables are in the array 
$matchCount = count($regexMatches);

if ($matchCount < 5){
    echo "less than 5";
}

Why is "less than 5" still being printed even though there's quite clearly 20 values in the $regexMatches array? What am I doing wrong?

Upvotes: 0

Views: 62

Answers (2)

Vytautas
Vytautas

Reputation: 3539

Why cant you just use preg_match_all return value:

$matchCount = preg_match_all($regexTags, $string, $regexMatches);
echo $matchCount;

Upvotes: 3

Kokos
Kokos

Reputation: 9121

Try count($regexMatches[0]).

:)

Upvotes: 4

Related Questions