简体   繁体   English

PHP preg_replace:从img以外的所有标签中删除style =“ ..”

[英]PHP preg_replace: remove style=“..” from all tags except img

It is the reverse of : PHP preg_replace: remove style=".." from img tags 与之相反: PHP preg_replace:从img标签中删除style =“ ..”

Im trying to find an expression for preg_replace, that deletes all inline css styles except for images. 我试图找到一个preg_replace表达式,该表达式删除除图像之外的所有内联css样式。 For example, I have this text: 例如,我有这段文字:

<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>

And I need to make it look like: 我需要使其看起来像:

<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>

or like this: 或像这样:

<img attribut="value" style="myCustom" attribut='value' style='myCustom' /> <input attribut="value" attribut='value'> <span attribut="value" attribut='value'> style= </span>

It might looks like this 可能看起来像这样

preg_replace('/(\<img[^>]+)(style\=\"[^\"]+\")([^>]+)(>)/', '${1}${3}${4}', $article->text)

The issue can be answered with a simple negative assertion: 可以使用简单的否定断言来回答问题:

preg_replace('/(<(?!img)\w+[^>]+)(style="[^"]+")([^>]*)(>)/', '${1}${3}${4}', $article->text)

And a simpler approach might be using (rather than fiddly DOMDocument): 一个更简单的方法可能是使用 (而不是的DOMDocument):

FORACH htmlqp($html)->find("*")->not("img") EACH $el->removeAttr("style");

This does as you've asked 正如您所要求的那样

$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);
}

OUTPUTS 输出值

<img attribut="value" style="myCustom" attribut='value' style='myCustom' /> <input attribut="value"  attribut='value' > <span attribut="value"  attribut='value' >  </span>

A very simple regular expression to get rid of them, without going too much into it would be 一个非常简单的正则表达式可以消除它们,而无需花太多精力

preg_replace( '/style="(.*)"/', 'REPLACEMENT' )

Very simple, effective enough though 很简单,虽然足够有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM