HTML中链接标签的正则表达式

5

我需要关于正则表达式的帮助。我正在寻找一个可以查找这样链接标签的正则表达式:

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

无论 href="" 在哪里,我都想在链接标签中查找它,并将一个名为 $url 的变量放在 style.css 前面,后跟一个斜杠。如果在 style.css 前面发现 http:// 或 https://,则不想在其前面放置变量。
我希望替换每个链接标记。
5个回答

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">

1
使用DOM解析器做这件事情有些过度(在我看来),罕见的文档是有效的(需要额外的处理),而DOM解析比正则表达式消耗更多的内存。 - Juicy Scripter
这是一个非常出色的答案。但是当链接元素使用单引号时,它会失败。我已经在我的答案中进行了扩展。请看这里。https://dev59.com/FUjSa4cB1Zd3GeqPJOGt#17441378 - Kim Stacks
看起来我无法使其适用于某些情况下的img元素。请在http://stackoverflow.com/questions/17441768/using-php-preg-replace-to-prepend-the-src-values-regardless-how-badly-formed-the上提供建议。 - Kim Stacks

2
这个问题不能用正则表达式很好地解决(也不够可靠),我建议使用 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>

2

请尝试使用这个正则表达式:

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

替换部分应如下所示。
\1http://\2\3

或者

$1http://$2$3

注意:根据您如何引用字符串,您可能需要转义其中一个引号。

谢谢,对我很有效。 - Ain Tohvri

0

我改编了@Juicy Scripter的答案。

这是对以下内容的改进。

a) it also works for single quotes as well as double quotes. meaning

/**
 *
 * 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;
    }


请注意,在某些情况下,此函数无法处理图像元素。一旦我得到http://stackoverflow.com/questions/17441768/using-php-preg-replace-to-prepend-the-src-values-regardless-how-badly-formed-the的答案,我会进行更新。 - Kim Stacks

-2

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

试试这个:

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

替换:href="<?php echo $url; ?>/\1"

如果你需要在PHP中使用它,使用preg_replace。只需记住你的搜索字符串需要在前后加上斜杠。


这也会影响超链接,例如 <a href="wherever">,所以不是一个好主意。 - Robert K
在文本编辑器或IDE中,您可以替换所选内容,在PHP中,通常可以将头部与正文分开解析。 - whichdan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接