moreyt25
moreyt25

Reputation: 33

Trying to replace height and width values in PHP

Trying to replace height="" and width="" values in a string($content) with PHP, i've tried preg replace to no avail, and suggestions on what i'm doing wrong?

Sample content would be:

$content = '<iframe width="560" height="315" src="http://www.youtube.com/embed/c0sL6_DNAy0" frameborder="0" allowfullscreen></iframe>';

Code below:

if($type === 'video'){

        $s = $content;
        preg_match_all('~(?|"([^"]+)"|(\S+))~', $s, $matches);

        foreach($matches[1] as $match){

            $newVal = $this->_parseIt($match);
    preg_replace($match, $newVal, $s);

        }

    }

Here i just take the match and search for my height and width

function _parseIt($match)
{
    $height = "height";
    $width = "width";

    if(substr($match, 0, 5) === $height){

        $pieces = explode("=", $match);
        $pieces[1] = "\"175\"";

        $new = implode("=", $pieces);
        return $new;

    } 

    if(substr($match, 0, 5) === $width){

        $pieces = explode("=", $match);
        $pieces[1] = "\"285\"";

        $new = implode("=", $pieces);
        return $new;

    }

    $new = $match;
    return $new;

}

There's probably a much shorter way to do this, however, I really just picked up programming 6 months ago.

Thanks in advance!

Upvotes: 3

Views: 6095

Answers (1)

xn.
xn.

Reputation: 16036

You can use preg_replace. It can take an array of regular expressions that you want to match and an array of replacements. You want to match width="\d+" and height="\d+". (If you're parsing arbitrary html, you'll want to extend the regex to match optional whitespace, single quotes, etc.)

$newWidth = 285;
$newHeight = 175;

$content = preg_replace(
   array('/width="\d+"/i', '/height="\d+"/i'),
   array(sprintf('width="%d"', $newWidth), sprintf('height="%d"', $newHeight)),
   $content);

Upvotes: 11

Related Questions