¿Necesita ayuda con simples expresiones regulares preg_match / preg_replace en php
-
18-09-2019 - |
Pregunta
Estoy tratando de hacer una simple tarea de alterar miles de códigos de integrar video musical con un común con / altura.
Por ejemplo, tengo el siguiente código:
<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>
Los saltos de línea adicionales sólo para la legibilidad
necesito para editar los parámetros de anchura / altura, tanto en las etiquetas <object>
y <embed>
, una de ellas con un sufijo 'px', y el otro no tener ninguno (que es totalmente al azar, algunos códigos tienen en todos los casos, Otros no lo hacen).
En primer lugar, estoy tratando de averiguar la anchura / altura del vídeo existente .... encontrar la relación de aspecto ... y volviendo a poner los valores existentes con los nuevos valores (width = "640" height = y "xxx" que se basa en la relación de aspecto del video).
Solución
Aquí es cómo conseguir la anchura y altura
preg_match('/width="(\d+)(px)?" height="(\d+)(px)?"/', $text, $matches);
$width = intval($matches[1]);
$height = intval($matches[3]);
Se calcula la nueva altura de esta manera:
$new_width = 640;
$new_height = intval($new_width * $height / $width);
Y sustituir de esta manera:
$text = preg_replace('/width="(\d+)(px)?" height="(\d+)(px)?"/',
'width="' . $new_width . '" height="' . $new_height . '"',
$text);
Otros consejos
$embed_clean = preg_replace('/width=([^"]"\d+(%|px|)[^"]")/','width="'.$CONFIG.'"',$embed_clean);
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();