我试图找到一个表达式preg_replace,删除所有内联css样式除了图像。例如,我有这样的文本: 我需要让它看起来像: 或者像这样: 它可能看起来像这样<img attribut="value" style="myCustom" attribut='value' style='myCustom' /> <input attribut="value" style="myCustom" attribut='value' style='myCustom'> <span attribut="value" style="myCustom" attribut='value' style='myCustom'> style= </span>
<img attribut="value" style="myCustom" attribut='value' style='myCustom' /> <input attribut="value" "myCustom" attribut='value' 'myCustom'> <span attribut="value" "myCustom" attribut='value' 'myCustom'> style= </span>
<img attribut="value" style="myCustom" attribut='value' style='myCustom' /> <input attribut="value" attribut='value'> <span attribut="value" attribut='value'> style= </span>
preg_replace('/('<img[^>]+)(style'='"[^'"]+'")([^>]+)(>)/', '${1}${3}${4}', $article->text)
正则表达式问题可以用一个简单的否定断言来回答:
preg_replace('/(<(?!img)'w+[^>]+)(style="[^"]+")([^>]*)(>)/', '${1}${3}${4}', $article->text)
更简单的方法可能是使用querypath(而不是繁琐的DOMDocument):
FORACH htmlqp($html)->find("*")->not("img") EACH $el->removeAttr("style");
这是您所要求的
$string = '<img attribut="value" style="myCustom" attribut=''value'' style=''myCustom'' /> <input attribut="value" style="myCustom" attribut=''value'' style=''myCustom''> <span attribut="value" style="myCustom" attribut=''value'' style=''myCustom''> style= </span>';
preg_match_all('/'<img.+?'/>/', $string, $images);
foreach ($images[0] as $i => $image) {
$string = str_replace($image,'--image'.$i.'--', $string);
}
$string = preg_replace(array('/style=['''"].+?['''"]/','/style=/'), '', $string);
foreach ($images[0] as $i => $image) {
$string = str_replace('--image'.$i.'--',$image, $string);
}
<img attribut="value" style="myCustom" attribut='value' style='myCustom' /> <input attribut="value" attribut='value' > <span attribut="value" attribut='value' > </span>
一个非常简单的正则表达式可以消除它们,而不需要过多地使用
preg_replace( '/style="(.*)"/', 'REPLACEMENT' )
非常简单,非常有效