如何使用php preg_replace将基本标签添加到头部标签


How to use php preg_replace to add base tag to head tag

我正在使用cURL请求输出一些代码。为了将相对地址更改为绝对地址,我想在head标签后面附加一个基标签。

我在想preg_replace可以做到这一点,但我不太确定regex。

我想添加这个标签

<base href="url">

在得到cURL请求的$输出中附加这个标签的正则表达式是什么?

这是我正在使用的cURL请求的代码。

$ch = curl_init();
// set a single option...
// ... or an array of options
curl_setopt($ch, CURLOPT_URL, $url);
    // Set a referer
    // User agent
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2");
    // Include header in result? (0 = yes, 1 = no)
    curl_setopt($ch, CURLOPT_HEADER, 0);
    // Should cURL return or print out the data? (true = return, false = print)
 curl_setopt($ch, CURLOPT_REFERER, $url); 
    // Timeout in seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
    // Download the given URL, and return output
    $output = curl_exec($ch);
 $output = str_replace('</head>','<base href="'.$href.'"></head>',$output);
//$output= preg_replace("/<head>/", "<head><base href=".$href.">", $output); 
 echo $output;
curl_close($ch);

首先,确保您的代码返回一个HTML字符串(curl_exec)

第二个,你不需要preg_replace…

$yourString = str_replace('</head>', '<base href="url"></head>', $yourString);