preg_match_all不符合这种模式

时间:2016-01-09 11:43:56

标签: php preg-match-all

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

不符合

<td>dddd

,而

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

工作正常。

我错过了什么吗?

1 个答案:

答案 0 :(得分:2)

我假设您的上面的dddd是数字,而不是字符dddd。 两个preg_match_all都有效,但第一个也匹配文本'&lt; td&gt;'。如果您只需要在()中对数字进行分组并获取该值而不是整个匹配。

<?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);


?>

输出:

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
        )

)