我需要关于正则表达式的帮助。我正在寻找一个可以查找这样链接标签的正则表达式:
<link rel="stylesheet" href="style.css" type="text/css">
无论 href="" 在哪里,我都想在链接标签中查找它,并将一个名为 $url 的变量放在 style.css 前面,后跟一个斜杠。如果在 style.css 前面发现 http:// 或 https://,则不想在其前面放置变量。
我希望替换每个链接标记。
我需要关于正则表达式的帮助。我正在寻找一个可以查找这样链接标签的正则表达式:
<link rel="stylesheet" href="style.css" type="text/css">
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">
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>
请尝试使用这个正则表达式:
/(<link.*href=["'])(style.css)(["'].[^>]*>)/gi
\1http://\2\3
或者
$1http://$2$3
我改编了@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;
}
我猜你正在编辑单个文件 - 你的文本编辑器或IDE应该能够为你执行正则表达式搜索/替换。
试试这个:
搜索:href="([^http].*?)"
替换:href="<?php echo $url; ?>/\1"
如果你需要在PHP中使用它,使用preg_replace。只需记住你的搜索字符串需要在前后加上斜杠。