您可以像这样使用 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">