替换链接位置(href ='...')

时间:2010-06-23 05:45:05

标签: php regex string preg-replace html-parsing

我想替换页面的链接位置(锚标记),如下所示。

示例输入:

text text text <a href='http://test1.com/'> click </a> text text
other text <a class='links' href="gallery.html" title='Look at the gallery'> Gallery</a>
more text

示例输出

text text text <a href='http://example.com/p.php?q=http://test1.com/'> click </a> text text
other text <a class='links' href="http://example.com/p.php?q=gallery.html" title='Look at the gallery'> Gallery</a>
more text

我希望我已经说清楚了。无论如何,我正在尝试使用PHP和reg-ex。请你点赞我吧。

谢谢 萨迪

2 个答案:

答案 0 :(得分:9)

不要使用正则表达式来解析HTML。

使用PHP的内置XML解析引擎。它在你的问题上运作得很好(并回答要引导的问题):

<?php
  libxml_use_internal_errors(true);  // ignore malformed HTML
  $xml = new DOMDocument();
  $xml->loadHTMLFile("http://stackoverflow.com/questions/3099187/replace-links-location-href"); 
  foreach($xml->getElementsByTagName('a') as $link) {
   $link->setAttribute('href', "http://www.google.com/?q=" . $link->getAttribute('href'));
  }
  echo $xml->saveHTML();  // output to browser, save to file, etc.

答案 1 :(得分:-1)

尝试使用str_replace();

   $string = 'your text';
   $newstring = str_replace ('href="', 'href="http://example.com/p.php?q=', $string);