【问题标题】:Invalid HTML - Quoting Attributes无效的 HTML - 引用属性
【发布时间】:2015-01-04 13:55:51
【问题描述】:

我有以下 HTML:

<td width=140 style='width:105.0pt;padding:0cm 0cm 0cm 0cm'>
    <p class=MsoNormal><span style='font-size:9.0pt;font-family:"Arial","sans-serif";
       mso-fareast-font-family:"Times New Roman";color:#666666'>OCCUPANCY
       TAX:</span></p>
</td>

一些 HTML 属性没有被引用,例如:width=140 和 class=MsoNormal

是否有任何 PHP 函数可以处理这类事情,如果没有的话,在 HTML 中清理它的聪明方法是什么?

谢谢。

【问题讨论】:

  • 没有原生的php函数,已经清理过了。 唯一真正需要"" 的时间是值中存在特殊字符或空格时。鉴于此,我认为最好自己清理文件,使用 sublime 等文本编辑器。
  • 我必须以编程方式解决这个问题。不带引号的 width=140 给我带来了麻烦,因为我使用的是quoted_printable_decode() 函数,当它发现 =140 时会将其转换为一些不受欢迎的字符。但是 with='140' (带引号)很好。但我想要一些巧妙的方式来引用整个文件中的所有属性。
  • 可能是a PHP DOM parser?
  • 我建议你不要使用内联样式。将您的样式与您的标记分开,它将为您省去很多麻烦。相信我。
  • @Nuno Aruda 这是我得到的 HTML,不是我写的。我必须使用它。

标签: php html quotes


【解决方案1】:

我猜你可以为此使用正则表达式:

/\s([\w]{1,}=)((?!")[\w]{1,}(?!"))/g


\s match any white space character [\r\n\t\f ]
1st Capturing group ([\w]{1,}=)
    [\w]{1,} match a single character present in the list below
        Quantifier: {1,} Between 1 and unlimited times, as many times as possible, giving back as needed [greedy]
    \w match any word character [a-zA-Z0-9_]
    = matches the character = literally
2nd Capturing group ((?!")[\w]{1,}(?!"))
    (?!") Negative Lookahead - Assert that it is impossible to match the regex below
    " matches the characters " literally
    [\w]{1,} match a single character present in the list below
        Quantifier: {1,} Between 1 and unlimited times, as many times as possible, giving back as needed [greedy]
    \w match any word character [a-zA-Z0-9_]
    (?!") Negative Lookahead - Assert that it is impossible to match the regex below
    " matches the characters " literally
g modifier: global. All matches (don't return on first match)

这将是这样实现的:

echo preg_replace_callback('/\s([\w]{1,}=)((?!")[\w]{1,}(?!"))/', function($matches){
    return ' '.$matches[1].'"'.$matches[2].'"';
}, $str);

会导致:

 <td width="140" style='width:105.0pt;padding:0cm 0cm 0cm 0cm'>
   <p class="MsoNormal"><span style='font-size:9.0pt;font-family:"Arial","sans-serif";
     mso-fareast-font-family:"Times New Roman";color:#666666'>OCCUPANCY
      TAX:</span></p>
 </td>

Eval.in live example

注意,这是一个肮脏的例子,当然可以清理。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-05
相关资源
最近更新 更多