【问题标题】:preg_match returns null when searching for escaped quotespreg_match 在搜索转义引号时返回 null
【发布时间】:2017-09-25 17:59:19
【问题描述】:

我正在从我的 Wordpress 数据库中检索一个字符串;我检索的字符串是一个纯文本字段,可以在其中添加 Wordpress 库。字符串的一些示例如下:

<p>test</p><p>[gallery columns=\"2\" ids=\"705,729\"]</p>
<p>[gallery columns=\"2\" ids=\"696,694\"]</p>
<p>test</p>

我想检索ids=\"x,x\" 字段中的数字。

我有以下代码:

for ($i = 1; $i<5; $i++) {
    $result = get_ids_per_category($i, getReferencesMapId());
    ${"idArray".$i} = array();
    foreach ($result as $res) {
        $subject = $res->description;
        $pattern = "/\[(.*?)\]/";
        preg_match($pattern,$subject,$matches);
        if ($matches[1]) {
            $subject2 = $matches[1];
            $pattern2 = '/ids=\\"(.*)\\"/';
            preg_match($pattern2, $subject2, $matches2);

            array_push( ${"idArray".$i}, $matches2);
        }
    }

    if (!empty(${"idArray".$i})) {
        ${"finalArray".$i} = array();
        foreach (${"idArray".$i} as $arr) {
            $newarray = explode(",",$arr[1]);
            foreach ($newarray as $item) {
                array_push( ${"finalArray".$i}, $item);
            }
        }
    }
}

如果我调用var_dump($subject2),会返回以下结果:

\page-referentiemap.php:58:string 'gallery columns=\"2\" ids=\"477,476\"' (length=37)
\page-referentiemap.php:58:string 'gallery columns=\"1\" ids=\"690\"' (length=33)
\page-referentiemap.php:58:string 'gallery ids=\"688,689,690\"' (length=27)
\page-referentiemap.php:58:string 'gallery columns=\"2\" ids=\"697,698,699\"' (length=41)
\page-referentiemap.php:58:string 'gallery ids=\"702,701,703\"' (length=27)
\page-referentiemap.php:58:string 'gallery columns=\"2\" ids=\"696,694\"' (length=37)

到目前为止一切顺利,但之后我创建正则表达式的行如下:

preg_match($pattern2, $subject2, $matches2);

将始终在 $matches2 中返回空值。

我不记得我在过去几周内更改了任何代码,这确实有效。谁能告诉我我错过了什么?

【问题讨论】:

    标签: php regex wordpress


    【解决方案1】:

    您需要两次转义反斜杠。一次用于 PHP,一次用于 PCRE。试试这个:

    $pattern2 = '/ids=\\\\"(.*)\\\\"/';
    

    虽然真的,您似乎可以使这段代码更简单。显然我无法完全测试,但似乎这应该有效:

    <?php
    $ids = [];
    for ($i = 1; $i<5; $i++) {
        $result = get_ids_per_category($i, getReferencesMapId());
        foreach ($result as $res) {
            $subject = $res->description;
            $pattern = '/\[.*?\\bids=\\\\"(\d+),(\d+)\\\\".*?\]/';
            if (preg_match($pattern,$subject,$matches)) {
                $ids[$i][] = [$matches[1], $matches[2]];
            }
        }
    }
    
    print_r($ids);
    

    除非您有充分的理由,否则您确实希望远离动态变量名称。数组几乎总是更可取的。

    【讨论】:

    • 非常感谢您成功了!你能告诉我为什么动态变量被认为是不好的做法吗?
    • 这是一个知道在任何给定时间存在哪些变量的问题。当您动态创建变量时,您正在为程序添加不确定性元素。当然,通过一个简单的for 循环创建少量固定数量的变量,这没什么大不了的。但在这种情况下,你将如何处理你的 5 个独立变量?大概您会想对它们中的每一个做一些事情,并且可以轻松地迭代数组。并且坚持常见的编程约定也可以让你的代码更容易被其他人阅读。我想我的问题是为什么要使用它们而不是数组?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    • 2022-10-17
    • 1970-01-01
    • 2011-06-26
    • 2018-08-01
    • 1970-01-01
    • 2014-03-06
    相关资源
    最近更新 更多