Replacing HTML attributes with regex in PHP

Well, I know that I should use the DOM parser, but this should drown out some code, which is a proof of concept for a later function, so I want to quickly get some functions on a limited set of test code.

I am trying to remove the width and height attributes of pieces of HTML, in other words, replace

width="number" height="number"

with an empty string.

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

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 does not work.

How do I do this job?

+5
source share
3 answers

PHP , , Python, Java #, , , Perl, JavaScript Ruby.

, , , . , .

, :

$pattern = '/(width|height)="[0-9]*"/i';
+7

/ . :

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

"/" - , ( "| pattern |", "# pattern #", ).

+4

I think you are missing the brackets (which may be //, || or various other pairs of characters) that should surround the regular expression in the string. Try changing the $ pattern assignment to this form:

$pattern = "/width=\"[0-9]*\"/";

... if you want to be able to do case-insensitive comparisons, add "i" to the end of the line, this way:

$pattern = "/width=\"[0-9]*\"/i";

Hope this helps! David

0
source

All Articles