【问题标题】:How to use php preg_replace to add base tag to head tag如何使用 php preg_replace 将 base 标签添加到 head 标签
【发布时间】:2015-08-07 12:23:34
【问题描述】:

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

我在想 preg_replace 可以解决问题,但我不太确定正则表达式。

我想添加这个标签

<base href="url">

将这个标签附加到 $output 我得到我的 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);

【问题讨论】:

  • $yourString = str_replace('', '', $yourString);
  • @MohammadAlabed 你应该把它作为一个答案,因为它比使用实际的正则表达式来解决这个小问题更明智

标签: php regex curl


【解决方案1】:

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

第二,不需要preg_replace,,,试试这个:

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

【讨论】:

  • 我已经尝试过了,但它不起作用这是我使用的代码 $output = str_replace('','',$output);
  • no .. 你的代码替换了开始标签 .. 你应该替换结束标签
  • 即使在那之后它也不起作用,我从 cURL 请求中获得了 $output 。这可能是个问题
  • 能否将您的代码添加到问题中,以便我们弄清楚
  • 你必须阅读 curl_exec 它返回布尔值,你必须设置 CURLOPT_RETURNTRANSFER = 1
猜你喜欢
  • 1970-01-01
  • 2011-03-14
  • 1970-01-01
  • 2014-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多