【问题标题】:preg_match_all won't match this patternpreg_match_all 与此模式不匹配
【发布时间】:2016-01-09 11:43:56
【问题描述】:
preg_match_all("/<td>\d{4}/i", $a, $b);

不匹配

<td>dddd

而

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

工作得很好。

我错过了什么吗?

【问题讨论】:

标签: php preg-match-all


【解决方案1】:

我假设您上面的 dddd 是数字,而不是字符 dddd。 preg_match_all 都可以工作,但第一个也可以匹配文本“

”。如果您只想要数字,则必须将它们分组在 () 中并获取该值而不是整个匹配项。
<?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
        )

)

【讨论】:

    猜你喜欢
    • 2011-10-01
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多