Wednesday, April 22, 2009

PHP - How to remove a HTML element property value

It's pretty simple but I know regular expressions can be tough sometimes. The code below will remove the width property regardless if it's value is enclosed with single or double quotes.

$str = preg_replace('/width\s*=\s*["\'].*["\']/','',$str);
Let's put it into a function and change width to a variable so that this code is more flexible:

function remove_property($property,$str){
return preg_replace('/'.$property.'\s*=\s*["\'].*["\']/','',$str);
}

$str = '<img src="image.jpg" width="200" height="230">';
$stripped_string = remove_property('width',$str);
Enjoy!

No comments:

Post a Comment