2015-09-18 111 views
0

我從某個API獲取iframe,並且在某些var中保存了該iframe。PHP查找並替換字符串中的html屬性

我想搜索「高度」並將其值更改爲其他值。與「滾動」相同。

例如:

<iframe src="someurl.com" width="540" height="450" scrolling="yes" style="border: none;"></iframe> 

PHP函數後的iframe將是:

我們必須改變 「高度」,以600像素和 「滾動」 沒有

<iframe src="someurl.com" width="540" height="600" scrolling="no" style="border: none;"></iframe> 

我用此代碼解決問題:

$iframe = preg_replace('/(<*[^>]*height=)"[^>]+"([^>]*>)/', '\1"600"\2', $iframe); 

的問題是,「的preg_replace」後運行它刪除後的「高度」的所有HTML屬性

感謝

+0

你最好用java腳本來做這件事。 – vbrmnd

+0

改用JavaScript。 。 –

+0

嗨, 我知道我可以在JavaScript中做到這一點的問題是我們如何能用PHP做同樣的解決方案?像使用「preg_replace」 – user2413244

回答

2

可以使用DOMDocument它。類似這樣的:

function changeIframe($html) { 

    $dom = new DOMDocument; 
    $dom->loadHTML($html); 
    $iframes = $dom->getElementsByTagName('iframe'); 
    if (isset($iframes[0])) { 
     $iframes[0]->setAttribute('height', '600'); 
     $iframes[0]->setAttribute('scrolling', 'no'); 
     return $dom->saveHTML($iframes[0]); 
    } else { 
     return false; 
    } 
} 

$html = '<iframe src="someurl.com" width="540" height="450" scrolling="yes" style="border: none;"></iframe>'; 

echo changeIframe($html); 

使用此方法,您可以根據需要修改iframe。

謝謝。

0

你要求一個例子:

$str = '<iframe src="someurl.com" width="540" height="450" scrolling="yes" style="border: none;"></iframe>'; 

$str = preg_replace('/height=[\"\'][0-9]+[\"\']/i', 'height="600"', $str); 
$str = preg_replace('/scrolling=[\"\']yes[\"\']/i', 'scrolling="no"', $str); 

echo $str; // -> '<iframe src="someurl.com" width="540" height="600" scrolling="no" style="border: none;"></iframe>' 
+0

嗨,如果高度值是靜態的,但不是動態值,那麼您的示例可以很好。 – user2413244

+0

如果使用單引號(如'height ='450''),原始高度不同('height =「768」')或使用大寫字母(例如'HEIGHT =「450」 ')。 – feeela

+0

我看到你的觀點@ user2413244。我更新了我的答案以適合您的需求 –

相關問題