PHP에서 간단한 preg_match/preg_replace regex에 대한 도움이 필요합니다.
-
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"및 height = "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