【问题标题】:Regular Expression for Link Tags in HTMLHTML中链接标签的正则表达式
【发布时间】:2010-11-19 09:19:25
【问题描述】:

我需要正则表达式方面的帮助。我正在寻找的是一个寻找这样的链接标签的正则表达式:

<link rel="stylesheet" href="style.css" type="text/css">

无论 href="" 的位置如何,我都想在链接标签中查找它,并将一个名为 $url 的变量放在 style.css 前面,并在后面加上 /。如果它在 style.css 前面找到 http:// 或 https://,那么我不想把变量放在它前面。

我希望替换每个链接标签。

【问题讨论】:

    标签: php regex html-parsing link-tag


    【解决方案1】:

    我改编了@Juicy Scripter 的回答。

    这是对以下方面的改进。

    a) 它也适用于单引号和双引号。意义

    /**
     *
     * Take in html content as string and find all the <script src="yada.js" ... >
     * and add $prepend to the src values except when there is http: or https:
     *
     * @param $html String The html content
     * @param $prepend String The prepend we expect in front of all the href in css tags
     * @return String The new $html content after find and replace. 
     * 
     */
        protected static function _prependAttrForTags($html, $prepend, $tag) {
            if ($tag == 'css') {
                $element = 'link';
                $attr = 'href';
            }
            else if ($tag == 'js') {
                $element = 'script';
                $attr = 'src';
            }
            else if ($tag == 'img') {
                $element = 'img';
                $attr = 'src';
            }
            else {
                // wrong tag so return unchanged
                return $html;
            }
            // this checks for all the "yada.*"
            $html = preg_replace('/(<'.$element.'\b.+'.$attr.'=")(?!http)([^"]*)(".*>)/', '$1'.$prepend.'$2$3$4', $html);
            // this checks for all the 'yada.*'
            $html = preg_replace('/(<'.$element.'\b.+'.$attr.'='."'".')(?!http)([^"]*)('."'".'.*>)/', '$1'.$prepend.'$2$3$4', $html);
            return $html;
        }
    

    【讨论】:

    【解决方案2】:

    试试这个正则表达式:

    /(<link.*href=["'])(style.css)(["'].[^>]*>)/gi 
    

    替换部分看起来像

    \1http://\2\3
    

    $1http://$2$3
    

    注意:您可能需要根据引用字符串的方式转义其中一个引号。

    【讨论】:

    • 谢谢。对我来说效果很好。
    【解决方案3】:

    您可以像这样使用 preg_replace 来归档所需的结果:

    preg_replace('/(<link\b.+href=")(?!http)([^"]*)(".*>)/', '$1'.$url.'$2$3$4', $html);
    

    所以这段代码(假设存储在$html和$url = 'http://mydomain.com/'):

    <link rel="stylesheet" href="style.css" type="text/css">
    <link rel="stylesheet" href="style2.css" type="text/css">
    <link rel="stylesheet" href="http://google.com/style3.css" type="text/css">
    <link rel="stylesheet" href="style4.css" type="text/css">
    <link rel="stylesheet" href="https://google.com/style5.css" type="text/css">
    <link rel="stylesheet" href="some/path/to/style6.css" type="text/css">
    

    会转换成这个:

    <link rel="stylesheet" href="http://mydomain.com/style.css" type="text/css">
    <link rel="stylesheet" href="http://mydomain.com/style2.css" type="text/css">
    <link rel="stylesheet" href="http://google.com/style3.css" type="text/css">
    <link rel="stylesheet" href="http://mydomain.com/style4.css" type="text/css">
    <link rel="stylesheet" href="https://google.com/style5.css" type="text/css">
    <link rel="stylesheet" href="http://mydomain.com/some/path/to/style6.css" type="text/css">
    

    【讨论】:

    • 使用 DOM 解析器执行此操作是过大的 (IMO) 稀有文档是有效的(并且需要额外的处理),并且 DOM 解析比正则表达式消耗更多的内存。
    • 这是一个极好的答案。但是当链接元素使用单引号时它失败了。我自己扩展了这个答案。看这里。 stackoverflow.com/a/17441378/80353
    • 看起来在某些情况下我无法将其调整为适用于 img 元素。请告知stackoverflow.com/questions/17441768/…
    【解决方案4】:

    使用正则表达式的解决方案永远不会很漂亮(或可靠),我建议改用 DOM 解析器,并使用其中一种操作方法添加属性。看看 simplehtmldom:

    http://simplehtmldom.sourceforge.net/

    例如,看看这个:

    // Create DOM from string
    $html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');
    
    $html->find('div', 1)->class = 'bar';
    
    $html->find('div[id=hello]', 0)->innertext = 'foo';
    
    echo $html; // Output: <div id="hello">foo</div><div id="world" class="bar">World</div>
    

    【讨论】:

      【解决方案5】:

      我猜您正在编辑单个文件 - 您的文本编辑器或 IDE 应该能够为您进行正则表达式搜索/替换。

      试试这个:

      搜索:href="([^http].*?)"

      替换:href="&lt;?php echo $url; ?&gt;/\1"

      如果您需要在 PHP 中使用它,请使用 preg_replace。请记住,您的搜索字符串前后都需要一个正斜杠。

      【讨论】:

      • 这也会影响超链接,例如 所以不是一个好主意。
      • 在文本编辑器或 IDE 中,您可以在选择中替换,而在 PHP 中,您通常可以将头部与正文分开解析。
      猜你喜欢
      • 1970-01-01
      • 2014-08-23
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-09
      相关资源
      最近更新 更多