1

我有一个 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?url=$link 替换 href 中的所有 url

我尝试:

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

4 回答 4

1

这可能会在短期内帮助您:

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

在您的正则表达式中,您使用href="..."的是双引号,即双引号,但在您的 HTML 中,您混合了双引号和单引号。

在替换字符串中,您忘记包含$1and $3

也就是说,不要使用正则表达式来解析 HTML。下面@BenLanc 的答案更好,请改用它。阅读他发布的链接。

于 2013-08-29T16:14:15.580 回答
1

不要在 HTML 上使用正则表达式,HTML 不是常规的。

假设您的标记是有效的(如果不是,请先通过Tidy传递),您应该使用xpath来获取元素,然后直接更新 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();
于 2013-08-29T16:20:20.473 回答
0

正则表达式匹配一个 url:

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

更多背景信息

于 2013-08-29T16:15:59.997 回答
0

不要忘记 /m 在您的正则表达式末尾,因为您使用的是多行源代码:

PHP 文档 PCRE

于 2013-08-29T16:18:01.647 回答