【问题标题】:php domdocument loadHTML with skipping error, or regex solutionphp domdocument loadHTML 跳过错误,或正则表达式解决方案
【发布时间】:2012-08-31 04:32:18
【问题描述】:

今天早些时候,我问了一个关于使用正则表达式解决方案来用 return fo 某个函数替换 html 中所有链接的 hrefs 的问题..

然后我删除了它,因为我似乎可以使用 DomDocument 解决它,但事实证明,我不能......

看到我的 html 有很多错误的 html 语法、html5 代码等等等。所以 loadHTML 和 loadXML 都不起作用..

如果有人可以使用正则表达式提供解决方案来查找 href 并使用调用所有函数进行替换..我尝试过 preg_replace 和 preg_replace_callback,但我无法理解 $1、$2..整个概念。 . 我搜索了所有类似的问题,但他们都有 DomDocumenet 的答案,我无法使用..

旧的类似问题: Grabbing the href attribute of an A element

Find all hrefs in page and replace with link maintaining previous link - PHP

但我需要正则表达式解决方案

【问题讨论】:

    标签: php html regex preg-replace preg-replace-callback


    【解决方案1】:

    试试这个代码:

    // $text - your text
    // $1 - preg variable for 1st "(.*)" match
    // $2 - preg variable for 2nd "(.*)" match
    preg_replace('/<a(.*)href="([^"]*)"(.*)>/','<a $1 href="http://new.href" $3>',$text);
    

    我在这里粘贴工作示例: http://codepad.org/KORtcb9q

    【讨论】:

    • thnx..similar 解决方案我已经实现了..liked..:)
    【解决方案2】:

    我创建了一个..通常人们害怕的主要问题是有其他属性,在 href 之前,在 href 之后,空格,有错误的 url 规范,单引号或双引号中的 href url 等等。最大的优势是我学会了如何使用它们..

    $callback = function ($match) use($params){
            $data = MyClass::updateUrl($match[2], $params);
            $return_data = 'href='.$match[1].$data.$match[1];
            return $return_data;
        };
        $reg = "#href\s*=\s*(\"|')?([^\"'>]+)(\"|')#i";
        return preg_replace_callback($reg, $callback, $html);
    

    【讨论】:

      猜你喜欢
      • 2012-05-18
      • 2018-11-21
      • 1970-01-01
      • 2012-02-27
      • 1970-01-01
      • 2010-10-25
      • 1970-01-01
      • 2013-09-29
      • 2023-03-14
      相关资源
      最近更新 更多