【问题标题】:replace all <a> tag to some character in php将所有 <a> 标记替换为 php 中的某个字符
【发布时间】:2014-04-07 06:43:46
【问题描述】:

我想在php中将&lt;a&gt;&lt;/a&gt;替换为[], 例如,如果我有:

This is sample test to say you &lt;a href="nowhere/333" id="blabah" &gt; help&lt;/a&gt; and you can redirect me to &lt;a href="dddd"&gt;answer&lt;/a&gt;

我想把它换成

This is sample test to say you [help] and you can redirect me to [answer],

如何使用正则表达式在 php 中完成这项工作?

【问题讨论】:

标签: php regex function dom output


【解决方案1】:

使用Document Object Model 并避免使用正则表达式来解析 HTML。

echo "[".$dom->getElementsByTagName('a')->item(0)->nodeValue."]";

Demo

代码..(编辑问题

<?php
$html='This is sample test to say you  <a href="nowhere/333" id="blabah" > help</a> and  you can redirect me to <a href="dddd">answer</a>';
$dom = new DOMDocument;
$dom->loadHTML($html);
$srch=array();$rep=array();
foreach($dom->getElementsByTagName('a') as $atag)
{
   $srch[]=trim($atag->nodeValue);
   $rep[]="[".trim($atag->nodeValue)."]";
}

echo str_replace($srch,$rep,strip_tags($html));

OUTPUT :

This is sample test to say you   [help] and  you can redirect me to [answer]

【讨论】:

  • 我们如何使用它?任何阅读链接或一些基本解释
  • 不,这不是在那里替换它们,我的文本有多个单词和行,我想用[]替换每个&lt;a&gt;&lt;/a&gt;标签
  • @zhilevan,好像你编辑了你的整个问题......-_-
  • 不,我不编辑整个问题,我只是在我的例子中添加一些文字来说明你我的测试不短
  • @stealthyninja 你为什么不在这里写下你的答案?
【解决方案2】:

搜索&lt;a.*?&gt;(.*?)&lt;\/a&gt; 并替换为[\1]

<?php
$html='<a href="nowhere/333" id="blabah" > help</a>';
echo preg_replace('/<a.*?>(.*?)<\/a>/', '[\1]', $html);

【讨论】:

  • 您的代码将在'&lt;a href="nowhere&gt;&lt;script&gt;alert('evil hacker here')&lt;/script&gt; 333" id="blabah" &gt; help&lt;/a&gt;'; 上失败
【解决方案3】:

答案应该交给 Shankar Damodaran,这是他为满足 OP 的要求而扩展的答案:

<?php
$html  = 'This is sample test to say you  <a href="nowhere/333" ';
$html .= 'id="blabah" > help</a> and  you can redirect me to <a ';
$html .= 'href="dddd">answer</a> it replaced to';

$dom = new DOMDocument;
$dom->loadHTML($html);

$elements = count($dom->getElementsByTagName('a'));

for ($i = 0; $i <= $elements; $i++) {
    echo "[" . trim($dom->getElementsByTagName('a')->item($i)->nodeValue) . "]";
}
?>

Extended Demo

【讨论】:

  • +1 mate ,但我认为他想替换整个东西,所以你需要 DOMDocument 类的replaceChild
猜你喜欢
  • 2014-06-03
  • 1970-01-01
  • 1970-01-01
  • 2017-12-14
  • 1970-01-01
  • 2017-04-13
  • 2016-07-20
  • 1970-01-01
  • 2011-04-05
相关资源
最近更新 更多