需要在PHP简单的preg_match /的preg_replace正则表达式帮助
-
18-09-2019 - |
题
我试图做改变成千上万的音乐视频嵌入代码有共同点/身高的一个简单的任务。
例如,我有以下代码:
<object width="480px" height="407px" >
<param name="allowFullScreen" value="true"/>
<param name="wmode" value="transparent"/>
<param name="movie" value="http://mediaservices.myspace.com/services/media/embed.aspx/m=1311720,t=1,mt=video"/>
<embed src="http://mediaservices.myspace.com/services/media/embed.aspx/m=1311720,t=1,mt=video"
width="480" height="407" allowFullScreen="true"
type="application/x-shockwave-flash"
wmode="transparent">
</embed>
</object>
<子> 仅是为了便于阅读加入换行符 子>
我需要在两个<object>
和<embed>
标记,一个具有“PX”后缀来编辑宽度/高度参数,以及其它不具有一个在所有(这是完全随机的,一些码具有它在所有情况下,别人不一样)。
首先,我试图找出存在的视频的宽度/高度....找到的纵横比...,然后用新的值代替现有值(宽度=“640”和高度=这是基于所述视频的纵横比“XXX”)。
解决方案
下面是如何获得的宽度和高度
preg_match('/width="(\d+)(px)?" height="(\d+)(px)?"/', $text, $matches);
$width = intval($matches[1]);
$height = intval($matches[3]);
计算这样的新高度:
$new_width = 640;
$new_height = intval($new_width * $height / $width);
和替换像这样:
$text = preg_replace('/width="(\d+)(px)?" height="(\d+)(px)?"/',
'width="' . $new_width . '" height="' . $new_height . '"',
$text);
其他提示
$embed_clean = preg_replace('/width=([^"]"\d+(%|px|)[^"]")/','width="'.$CONFIG.'"',$embed_clean);
使用 SimpleHTMLDOM :
require_once("simplehtmldom.php");
$dom = str_get_html($text);
foreach ($dom->find('object') as $obj) {
$width = intval($obj->width);
$height = intval($obj->height);
$height = intval(640 * $height / $width);
$obj->width = 640;
$obj->height = $height;
$embed = $obj->find('embed',0);
if ($embed != null) {
$embed->width = 640;
$embed->height = $height;
}
}
$text = $dom->save();
不隶属于 StackOverflow