开发者

Preg_replace image inner style [duplicate]

开发者 https://www.devze.com 2023-04-10 18:37 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Best methods to parse HTML with PHP开发者_运维技巧
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Best methods to parse HTML with PHP

开发者_运维技巧

For a website I have strings without knowing what text or image lines there will be in them. I want to create a replacement for the image inner style. The whole style="" must be removed without knowing what styles will be between "".

What is the pattern for the replace I need.


It is a bad idea to use a regular expression for this, since an HTML parser will be much more robust. If the style attribute is always going to be similar, with just minor variations, then you can use the following to change it:

$yourStyle = 'style="your-style-goes-here"';
$newString = preg_replace('%style="(.*?)"%is', $yourStyle, $string);

If you just want to remove the style attribute completely, then set $yourStyle = '';

Again, this is not the best way to do this, but it will work assuming that you never have a quotation mark in the middle of the style and that the style attribute ends with a quotation mark.


Something like this should help:

$data = array(
    '<img src="hello/test.png" />',
    '<img src="hello/test.png"/>',
    '<img src="hello/test.png">',
    '<img src="mama" style="blabla; background-color: #98473; border: 1px solid black" border="0" />',
    '<img src="mama" style="blabla; background-color: #98473; border: 1px solid black" border="0"/>',
    '<img src="mama" style="blabla; background-color: #98473; border: 1px solid black" border="0">',
    '<img src="mama" style="blabla; background-color: #98473; border: 1px solid black" />',
    '<img src="mama" style="blabla; background-color: #98473; border: 1px solid black"/>',
    '<img src="mama" style="blabla; background-color: #98473; border: 1px solid black">',
    '<img style="blabla; background-color: #98473; border: 1px solid black" src="mama" />',
    '<img style="blabla; background-color: #98473; border: 1px solid black" src="mama"/>',
    '<img style="blabla; background-color: #98473; border: 1px solid black" src="mama">',
);
foreach($data as $texttosearch){
    echo htmlentities($texttosearch).' => '.htmlentities(preg_replace('/(<img .*?)(style=("|\').*?("|\'))(.*?(\/?)>)/i', '$1$5', $texttosearch)).'<br />';
}


This should help:

/(?:style=")(?:[\w\-\:\;\s\%\#]+)(?:\")/i

It will strip majority of style attributes from any tag. You can place it in a function and feed it the parts you want to check/replace

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号