【问题标题】:Get other part of array when match found找到匹配时获取数组的其他部分
【发布时间】:2015-12-21 10:10:53
【问题描述】:

这是我正在使用的正则表达式。它工作正常,但现在我正在尝试获得结果。

基本上,如果名称/属性/等包含“标题”,我希望它回显标题元标记的内容。

换句话说,当out[1]包含“title”(不区分大小写)时,我想要对应的out[2],而不是out[1]。

  $pattern = '
  ~<\s*meta\s

  # using lookahead to capture type to $1
    (?=[^>]*?
    \b(?:name|property|http-equiv)\s*=\s*
    (?|"\s*([^"]*?)\s*"|\'\s*([^\']*?)\s*\'|
    ([^"\'>]*?)(?=\s*/?\s*>|\s\w+\s*=))
  )

  # capture content to $2
  [^>]*?\bcontent\s*=\s*
    (?|"\s*([^"]*?)\s*"|\'\s*([^\']*?)\s*\'|
    ([^"\'>]*?)(?=\s*/?\s*>|\s\w+\s*=))
  [^>]*>

  ~ix';

if(preg_match_all($pattern, $link_html, $out))
{
    foreach ($out[1] as $out)
    {
        echo $out.'<br>';
    }   
}

【问题讨论】:

  • 为什么不使用 html 解析器呢?

标签: php arrays regex title


【解决方案1】:

您要求使用正则表达式,但使用 HTML 解析器和 XPath 会更容易且更具可读性:

<?php

$html = <<< HTML
<html>
    <head>
        <meta name="author" lang="en" content="Gordon" />
        <meta name="title" lang="en" content="match this" />
        <meta property="title" lang="en" content="and this" />
        <meta http-equiv="title" lang="en" content="and also this" />
        <meta foo="title" content="but not this" />
    </head>
    <body>Use DOMDocument for HTML parsing instead</body>
</html>
HTML;

libxml_use_internal_errors(true);
$dom = new DOMDocument;
$dom->loadHTML($html);
libxml_use_internal_errors(false);

$xpath = new DOMXPath($dom);
$nodes = $xpath->evaluate(
    '//meta[
       @*[
         contains("name|property|http-equiv", name())
         and contains(., "title")
         ]
       ]/@content'
);

foreach ($nodes as $node) {
    echo $node->nodeValue, PHP_EOL;
}

输出:

match this
and this
and also this

XPath 意味着查找任何元标记的所有内容属性,其中任何属性名称是字符串“name|property|http-equiv”的一部分并且包含值“title”那个属性。

正如您所希望看到的,XPath 本身读起来几乎就像是自然语言(与您使用的正则表达式相反)。

【讨论】:

  • 哦,哇,我很久以前就用过 XPath,然后就忘了它……你说得对……当它允许我时,我会接受的。 ... 谢谢! :)
【解决方案2】:

这应该可以通过在foreach 循环中捕获数组索引来实现,如下所示:

foreach ($out[1] as $index => $out) {
    if(stristr($out, 'title')) echo $out[2][$index].'<br>';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多