2013-02-06 2 views
2

필자 내가 SRC = "www.youtube로 시작하는 SRC를 포함하는 경우에만 iframe을 대상으로 지정할PHP/워드 프레스는 preg_match

사업부 클래스 ="비디오 컨테이너 "의 모든 iframe이의 포장 다음과 같은 기능을 가지고

구체적 않는이 기능을 수정하는 방법이

인가?

감사합니다 사전에.

function div_wrapper($content) { 
// match any iframes 
$pattern = '~<iframe.*</iframe>~'; 
preg_match_all($pattern, $content, $matches); 

foreach ($matches[0] as $match) { 
    // wrap matched iframe with div 
    $wrappedframe = '<div class="video-container">' . $match . '</div>'; 

    //replace original iframe with new in content 
    $content = str_replace($match, $wrappedframe, $content); 
} 

return $content;  
} 
add_filter('the_content', 'div_wrapper'); 
+0

foreach의 첫 번째 줄에'if (! condition) continue; '가 있습니다. 조건을 타겟 조건으로 만드십시오 (src는 무엇이든 시작합니다). – Patashu

답변

0

게으른 경기 (*?) 및 c를 수행 당신이 찾고있는 문자열이 존재한다면 도대체 :

// match any iframes 
$pattern = '~<iframe.*?</iframe>~'; 
$content = preg_replace_callback($pattern, function($matches){ 

    if(strpos($matches[0], 'youtube') !== false) 
    return '<div class="video-container">' . $matches[0] . '</div>'; 

    return $matches[0]; 

}, $content); 

물론 많은 경우에 실패 할 것입니다. 당신이 뭔가 안정적인 사용을 XML 파서를 원하는 경우 (DomDocument::getElementsByTagNameDomElement::getAttribute를 참조하십시오.

또한 :before 또는 :after 같은 의사 셀렉터와 iframe이 스타일을 시도 할 수 있습니다. 당신이 래퍼 요소가 필요하지 않습니다 그런 식으로 (예. iframe[src~=youtube]:after)

+0

아아, iframe을 래핑하기 위해 의사 코드를 사용하는 것을 생각하지 않았습니다. 아프게 그들에게 가자. – user1385827

+0

: before 의사 요소는 내 테스트 및이 게시물에 따라 작동하지 않습니다. http://stackoverflow.com/a/13056674/1385827 – user1385827

+0

위에 제공된 php가 작동합니다. 왜 당신은 그것이 많은 경우에 실패 할 것이라고 말하는지 확신 할 수 없습니까? 도와 줘서 고마워. – user1385827

0

난 그냥 $pattern 변수를 변경할 필요가 있다고 생각하여보십시오.

$pattern = '~<iframe.*src*=\'.*(http\:?)*\/\/*(www\.?)*youtube\..*</iframe>~'; 

참고 : @ 알렉스는 지적, 당신은 프로토콜 누락, 그래서 01이어야한다, //youtube. 또는 http://www.youtube.

+0

프로토콜이 누락되어 작동하지 않아야하므로 'iframe'이 작동하지 않습니다. – alex

+0

@alex : 질문에 빠졌기 때문에 잊어 버린 점에 감사드립니다 ... 업데이트 됨 –

+0

문자 클래스에서 그것을 원하지 않는다고 생각합니다. 선택 사항 인 경우 괄호를 사용하여 묶습니다. – alex