【问题标题】:remove all attributes in php but keep href, terget, rel in link as is删除 php 中的所有属性,但保留链接中的 href、terget、rel 原样
【发布时间】:2013-10-16 16:08:20
【问题描述】:

请向我推荐 preg_replacePHP 正则表达式,以便在不删除标签的情况下从 HTML 代码中的标签中删除所有属性。但是在超链接中,所有属性,如 href、terget、rel 都应该保持原样

请参考以下示例:

我已经用 preg_replace 尝试了 regex

$htmltext = '<p style="float: left;">
<span style="color: #ff0000;">
<b>Some text here</b>
</span>
<a target="_blank" rel="nofollow" href="http://thebankexam.com/page/7017">Clickable Text</a>
</p>';
$my_output = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i",'<$1$2>',$htmltext);
echo $my_output;

过滤后的输出 ($my_output):

<p>
<span>
<b>Some text here</b>
</span>
<a>Clickable Text</a>  <!-- Check this hyper link href, rel and target gone -->
</p>

预期的输出应如下所示:

<p>
<span>
<b>Some text here</b>
</span>
<a target="_blank" rel="nofollow" href="http://thebankexam.com/page/7017">Clickable Text</a>
</p>

【问题讨论】:

  • 是欧文,除了可点击的链接属性
  • 我有下面的正则表达式,但它也删除了 href、rel 和 target,只保留 &lt;a&gt;Clickable Text&lt;/a&gt; REGEX: preg_replace("/&lt;([a-z][a-z0-9]*)[^&gt;]*?(\/?)&gt;/i",'&lt;$1$2&gt;',$htmltext)
  • 这有一些我见过的最精神的答案。显然,如果没有 Chuck norris,这是不可能的
  • 当您仅从可点击链接中提及时,这是否意味着您想要删除那些不在可点击链接中的属性(href、target、rel)?

标签: php regex attributes href except


【解决方案1】:
preg_replace('/<a\s+[^>]*href\s*=\s*"([^"]+)"[^>]*>/', '<a href="\1">', $html);

【讨论】:

  • @OwenBeresford 你是什么意思?我想你不明白我的代码在做什么。
  • 任务规范说删除属性不是锚的一部分。 OP 在我的第一条评论中更新了任务。您的正则表达式仅匹配锚点。
  • @Marek 如果字符串为&lt;a href='http://somedomain.com' target='_blank'&gt;,这将不匹配单引号
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多