Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing HTML attributes using a regex in PHP

OK,I know that I should use a DOM parser, but this is to stub out some code that's a proof of concept for a later feature, so I want to quickly get some functionality on a limited set of test code.

I'm trying to strip the width and height attributes of chunks HTML, in other words, replace

width="number" height="number"

with a blank string.

The function I'm trying to write looks like this at the moment:

function remove_img_dimensions($string,$iphone) {
    $pattern = "width=\"[0-9]*\"";
    $string = preg_replace($pattern, "", $string);

    $pattern = "height=\"[0-9]*\"";
    $string = preg_replace($pattern, "", $string);

    return $string;
}

But that doesn't work.

How do I make that work?

like image 624
Rich Bradshaw Avatar asked Apr 22 '09 14:04

Rich Bradshaw


2 Answers

PHP is unique among the major languages in that, although regexes are specified in the form of string literals like in Python, Java and C#, you also have to use regex delimiters like in Perl, JavaScript and Ruby.

Be aware, too, that you can use single-quotes instead of double-quotes to reduce the need to escape characters like double-quotes and backslashes. It's a good habit to get into, because the escaping rules for double-quoted strings can be surprising.

Finally, you can combine your two replacements into one by means of a simple alternation:

$pattern = '/(width|height)="[0-9]*"/i';
like image 163
Alan Moore Avatar answered Oct 13 '22 11:10

Alan Moore


Your pattern needs the start/end pattern character. Like this:

$pattern = "/height=\"[0-9]*\"/";
$string = preg_replace($pattern, "", $string);

"/" is the usual character, but most characters would work ("|pattern|","#pattern#",whatever).

like image 44
Piskvor left the building Avatar answered Oct 13 '22 12:10

Piskvor left the building