3

文字列 ($content) の height="" と width="" の値を PHP に置き換えようとしていますが、preg replace を試してみましたが、うまくいきませんでした。

サンプル コンテンツは次のようになります。

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

以下のコード:

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);

        }

    }

ここでは、一致を取得して、高さと幅を検索します

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;

}

これを行うにはもっと短い方法があるかもしれませんが、私はちょうど 6 か月前にプログラミングを始めたばかりです。

前もって感謝します!

4

1 に答える 1

11

使用できますpreg_replace。一致させたい正規表現の配列と置換の配列を取ることができます。と を一致させたいwidth="\d+"としheight="\d+"ます。(任意の html を解析している場合は、オプションの空白、単一引用符などに一致するように正規表現を拡張する必要があります。)

$newWidth = 285;
$newHeight = 175;

$content = preg_replace(
   array('/width="\d+"/i', '/height="\d+"/i'),
   array(sprintf('width="%d"', $newWidth), sprintf('height="%d"', $newHeight)),
   $content);
于 2012-04-25T15:24:43.683 に答える