【问题标题】:PHP regex matches and include groups in each match (full match)PHP 正则表达式匹配并在每个匹配中包含组(完全匹配)
【发布时间】:2020-10-12 01:42:21
【问题描述】:

基本上,我的变量包含 html 代码,其中有一个我尝试捕获的 url。 我能够捕获它,但我忘记了哪些标志或方法将组包含在匹配项中

  $xxx = 'icon-2525 attributeIcon-2521" focusable="false" height="100%" role="img" 
  width="100%"><use xlink:href="#icon-clipboard"></use></svg><dl class="itemAttribute-1524"><dd 
  class="attributeValue-3783238563"><a class="attributeLink-387024144" rel=" noopener noreferrer" 
  href="https://tld.example.com/en/main?id=325235231763265&amp;ref=testetghe" 
  title="Opens in a new window." target="_blank"';

preg_match_all("/https:\/\/tld.example.com(.*?)ref=testetghe\"/is", $xxx, $matches);
foreach($matches[1] as $url);

foreach 会将 $url 正确设置为 (/en/main?id=325235231763265&amp) 但我希望 $url 成为完整的 url (https://tld.example.com/en/main?id=325235231763265&ref=testetghe)

我会怎么做?这是我必须改变的标志吗?我在 regex101 上尝试了很多 在这里它的工作 https://regex101.com/r/jguNDZ/1

但我想要完整匹配输出。非常感谢 谢谢

【问题讨论】:

  • 当你的名字是DOMDocument时很有趣,但是使用正则表达式来解析HTML,使用索引零来获得匹配
  • 感谢 Kevin,但变量也可能包含 xml、csv、制表符分隔、超级循环、数据头等

标签: php regex


【解决方案1】:

当您使用preg_match_all 时。您将拥有与您的正则表达式匹配的所有值。使用print_r($matches)后,会看到如下输出:

Array
(
    [0] => Array
        (
            [0] => https://tld.example.com/en/main?id=325235231763265&amp;ref=testetghe"
        )

    [1] => Array
        (
            [0] => /en/main?id=325235231763265&amp;
        )

)

因此,您需要使用$matches[0] 而不是$matches[1]

【讨论】:

    【解决方案2】:

    如果您需要完整的 url,则使用 preg_match 函数并在匹配项的 0 索引处获取匹配项。

    $div = 'icon-2525 attributeIcon-2521" focusable="false" height="100%" role="img" 
    width="100%"><use xlink:href="#icon-clipboard"></use></svg><dl class="itemAttribute-1524"><dd 
    class="attributeValue-3783238563"><a class="attributeLink-387024144" rel=" noopener noreferrer" 
    href="https://tld.example.com/en/main?id=325235231763265&amp;ref=testetghe" 
    title="Opens in a new window." target="_blank"';
    
    $pattern = '/https:\/\/tld.example.com(.*?)ref=testetghe\"/is';
    preg_match( $pattern, $div, $matches);
    
    var_dump( $matches[0] ); 
    

    【讨论】:

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