user2218567
user2218567

Reputation: 94

preg_match_all won't match this pattern

preg_match_all("/<td>\d{4}/i", $a, $b);

does not match

<td>dddd

whereas

preg_match_all("/\d{4}/i", $a, $b);

works just fine.

Am I missing something?

Upvotes: 0

Views: 35

Answers (1)

Snorre L&#248;v&#229;s
Snorre L&#248;v&#229;s

Reputation: 271

I assume your dddd above is numbers, not the characters dddd. Both of the preg_match_all work, but the first would also match the text '<td>'. If you want only the numbers you have to group them in () and fetch that value instead of the whole match.

<?php

$a = "<td>1234";


$match_count = preg_match_all("/\d{4}/i", $a, $b);
print "Found: $match_count matches with /\d{4}/i\n";
print_r($b);

$match_count = preg_match_all("/<td>\d{4}/i", $a, $b);
print "Found: $match_count matches with /<td>\d{4}/i\n";
print_r($b);

#get the number in a grouping
$match_count = preg_match_all("/<td>(\d{4})/i", $a, $b, PREG_SET_ORDER);
print "Found: $match_count matches with /<td>(\d{4})/i\n";
print_r($b);


?>

Output:

Found: 1 matches with /\d{4}/i
Array
(
    [0] => Array
        (
            [0] => 1234
        )

)
Found: 1 matches with /<td>\d{4}/i
Array
(
    [0] => Array
        (
            [0] => <td>1234
        )

)
Found: 1 matches with /<td>(\d{4})/i
Array
(
    [0] => Array
        (
            [0] => <td>1234
            [1] => 1234
        )

)

Upvotes: 2

Related Questions