Php 正则表达式替换html页面中的url

Php 正则表达式替换html页面中的url,php,html,regex,Php,Html,Regex,我有一个html页面 <tr> <td rowspan="7"> <a href="http://www.link1.com/" style="text-decoration: none;"> <img src="image1.jpg" width="34" height="873" alt="" style="display:block;border:none" /> </a> </td&

我有一个html页面

<tr>
<td rowspan="7">
<a href="http://www.link1.com/" style="text-decoration: none;">
        <img src="image1.jpg" width="34" height="873" alt="" style="display:block;border:none" />
        </a>
    </td>
    <td colspan="2" rowspan="2">
        <a href='http://www.link1.com/test.php?c=1'>
        <img src="image1.jpg" width="287" height="146" alt="" style="display:block;border:none" />
        </a>
    </td>
<td colspan="2" rowspan="2">
        <a href='http://www.url.com/test.php?c=1'>
        <img src="image1.jpg" width="287" height="146" alt="" style="display:block;border:none" />
        </a>
    </td>

我想用mytest.com替换href中的所有url?url=$link

我尝试:

    $messaget = preg_replace('/<a(.*)href="([^"]*)"(.*)>/','mytest.com?url=$2',$messaget);

$messaget=preg_replace('/这可能在短期内对您有所帮助:

preg_replace('/<a (.*)href=[\'"]([^"]*)[\'"](.*)>/', '<a $1href="mytest.com?url=$2"$3>', $messaget);
preg\u replace(”/he发布。

Regex匹配url:

/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/  

不要忘记regexp末尾的/m,因为您使用的是多行源:

假设您的标记有效(如果无效,请先将其传递),您应该使用、获取元素,然后直接更新href。例如:

<?php
$messaget = <<<XML
<tr>
  <td rowspan="7">
    <a href="http://www.link1.com/" style="text-decoration: none;">
      <img src="image1.jpg" width="34" height="873" alt="" style="display:block;border:none" />
    </a>
  </td>
  <td colspan="2" rowspan="2">
      <a href='http://www.link1.com/test.php?c=1'>
      <img src="image1.jpg" width="287" height="146" alt="" style="display:block;border:none" />
      </a>
  </td>
  <td colspan="2" rowspan="2">
      <a href='http://www.url.com/test.php?c=1'>
      <img src="image1.jpg" width="287" height="146" alt="" style="display:block;border:none" />
      </a>
  </td>
</tr>
XML;

$xml   = new SimpleXMLElement($messaget);

// Select all "a" tags with href attributes
$links = $xml->xpath("//a[@href]");

// Loop through the links and update the href, don't forget to url encode the original!
foreach($links as $link)
{
  $link["href"] = sprintf("mytest.com/?url=%s", urlencode($link['href']));
}

// Return your HTML with transformed hrefs!
$messaget = $xml->asXml();
xpath(“//a[@href]”);
//循环浏览链接并更新href,不要忘记对原始url进行编码!
foreach($links作为$link)
{
$link[“href”]=sprintf(“mytest.com/?url=%s”,urlencode($link['href']);
}
//用转换后的HREF返回您的HTML!
$messaget=$xml->asXml();

PHP是服务器端代码…因此我不确定您试图实现的结果是什么/如何实现的。抱歉…我的html代码是变量$messaget。您不应该使用正则表达式来处理html代码,而应该使用html解析器。请参阅和。他的正则表达式仅适用于双引号。问题是,他需要根据自己的情况同时考虑双引号和单引号提供的示例。因此,您提供的正则表达式仍然无法完成此任务。虽然您已修复了替换错误,但您是对的。我之前没有看到他也使用双引号,我只看到了单引号。谢谢,现在将修复。@janos很酷,在您更新答案时取消了否决票并删除了我的评论