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>

href のすべての URL を mytest.com?url=$link に置き換えたい

私は試してみます:

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

4 に答える 4

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 に答える