【问题标题】:Regex matching specific html tags正则表达式匹配特定的 html 标签
【发布时间】:2023-03-24 03:55:01
【问题描述】:

我正在做表单,让用户向我发送包含图像链接的 html 代码。像这样:

<a href="http://linklocation.com" target="_blank"><img src="http://imagelocation.com" border="0"></a> 
<a href="http://linklocation.com" target="_blank"><img src="http://imagelocation.com" border="0"></a> 
<a href="http://linklocation.com" target="_blank"><img src="http://imagelocation.com" border="0"></a> 
<a href="http://linklocation.com" target="_blank"><img src="http://imagelocation.com" border="0"></a> 
<a href="http://linklocation.com" target="_blank"><img src="http://imagelocation.com" border="0" width="100px" height="100px"></a> <br>

现在我尝试使用 RegEx 仅选择 a 和 img HTML 标签,其中 img 可以是 &lt;img /&gt;、&lt;img&gt; &lt;/img&gt; 或 &lt;img&gt;。我现在还没有设置宽度、高度或其他东西,但它们也应该与 RegEx 一起出现。如果有任何其他 HTML 标记,则它不应该与 RegEx 一起提供。

所以基本上如果有这样的HTML代码:

<a href="http://linklocation.com" target="_blank"><img src="http://imagelocation.com" border="0"></a> 
<a href="http://linklocation.com" target="_blank"><p>Hello world!</p></a> <script>Something</script> 
<a href="http://linklocation2.com" target="_blank"><img src="http://imagelocation2.com" border="0" width="200px" height="20px"></a> 

RegEx 应该返回这些:

<a href="http://linklocation.com" target="_blank"><img src="http://imagelocation.com" border="0"></a> 
<a href="http://linklocation2.com" target="_blank"><img src="http://imagelocation2.com" border="0" width="200px" height="20px"></a> 

我希望你明白我在寻找什么。

【问题讨论】:

  • 你不应该使用正则表达式来解析 html 解释 here 如果你仍然想这样做,添加你的风格(你是什么语言)

标签: html regex


【解决方案1】:

您的正则表达式解决方案是:

/<a\s*.*?><img\s*.*?<\/a>/

PHP 示例:

$string = '<YOUR TEXT HERE>';
preg_match_all('#<a\s*.*?><img\s*.*?</a>#', $string, $matches);
print_r($matches[0]);

JavaScript 示例:

var string = '<YOUR TEXT HERE>';
var matches = string.match(/<a\s*.*?><img\s*.*?<\/a>/g);
console.log(matches)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    相关资源
    最近更新 更多