【问题标题】:Removing single and double quote from html attributes with no white spaces on all attributes except href and src从 html 属性中删除单引号和双引号,除 href 和 src 之外的所有属性都没有空格
【发布时间】:2014-05-11 00:25:33
【问题描述】:

我正在尝试从 html 属性中删除单引号和双引号,这些属性是没有空格的单个单词。我写了这个确实有效的正则表达式:

/((type|title|data-toggle|colspan|scope|role|media|name|rel|id|class|rel)\s*(=)\s*)(\"|\')(\S+)(\"|\')/ims

我没有指定所有要删除引号的 html 标记,而是仅列出要忽略的几个属性,例如 src 和 href,并删除所有其他属性名称上的引号。所以我写了下面的,但对我的生活来说它不起作用。它有些方法必须检测除 href 和 src 之外的任何属性名称。我尝试了各种组合。

/((?!href|src)(\S)+\s*(=)\s*)(\"|\')(\S+)(\"|\')/i

我已经尝试过了,但它不起作用。它只是从 href 和 src 的属性中删除 h 和 s。我知道我很接近但缺少一些东西。我在这上面花了 5 个小时。

工作示例

$html_code = 'your html code here.';

preg_replace('/((type|title|data-toggle|colspan|scope|role|media|name|rel|id|class|rel)\s*(=)\s*)(\"|\')(\S+)(\"|\')/i', '$1$5', "$html_code");

【问题讨论】:

标签: html regex html-parsing


【解决方案1】:

我修改了您编写的较小的 RegEx,结果如下:

((\S)+\s*(?<!href)(?<!src)(=)\s*)(\"|\')(\S+)(\"|\')

解析您的版本时,前瞻将到达文档中“href”之前的某个“h”并失败,然后继续执行下一个字符。由于 'ref' 不匹配 'href' 或 'src',你的模式的其余部分将匹配。

通过我的修改,任何 'href' 或 'src' 最初都会被正则表达式接受。当达到lookbehind时,它会在已经解析的文本中检查'href',如果找到就会失败。

【讨论】:

    【解决方案2】:

    此外,最好不要过滤hrefsrc 属性,而是过滤掉=。这是一个很好的正则表达式(这个正则表达式还假定所有属性都使用双引号):

    // Remove all double quote with attribute that have no space and no `=` character.
    $html = preg_replace('/((\S)+\s*(=)\s*)(\")(\S+(?<!=.))(\")/', '$1$5', $html);
    

    【讨论】:

      猜你喜欢
      • 2015-07-15
      • 2011-11-19
      • 2014-07-27
      • 1970-01-01
      • 2013-06-22
      • 1970-01-01
      • 2013-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多