php
  • regex
  • preg-replace
  • 2012-04-25 4 views 2 likes 
    2

    PHP에서 문자열 ($ content)의 height = ""및 width = ""값을 바꿔 쓰려고 시도했지만, 아무런 쓸모가없는 것으로 대체하려고했습니다. 및 제안 사항 내가 잘못하고있어?PHP에서 높이 및 너비 값을 바꾸려고 시도했습니다

    샘플 내용은 다음과 같습니다 아래

    $content = '<iframe width="560" height="315" src="http://www.youtube.com/embed/c0sL6_DNAy0" frameborder="0" allowfullscreen></iframe>'; 
    

    코드 :

    여기
    if($type === 'video'){ 
    
         $s = $content; 
         preg_match_all('~(?|"([^"]+)"|(\S+))~', $s, $matches); 
    
         foreach($matches[1] as $match){ 
    
          $newVal = $this->_parseIt($match); 
        preg_replace($match, $newVal, $s); 
    
         } 
    
        } 
    

    난 그냥 경기를 가지고 내 높이를 검색하고 아마 훨씬

    function _parseIt($match) 
    { 
        $height = "height"; 
        $width = "width"; 
    
        if(substr($match, 0, 5) === $height){ 
    
         $pieces = explode("=", $match); 
         $pieces[1] = "\"175\""; 
    
         $new = implode("=", $pieces); 
         return $new; 
    
        } 
    
        if(substr($match, 0, 5) === $width){ 
    
         $pieces = explode("=", $match); 
         $pieces[1] = "\"285\""; 
    
         $new = implode("=", $pieces); 
         return $new; 
    
        } 
    
        $new = $match; 
        return $new; 
    
    } 
    

    있다 폭 짧은 방법, 그러나, 나는 정말로 방금 6 개월 전에 프로그래밍을 집어 들었다.

    미리 감사드립니다.

    +0

    _parseIt()의 행 3은 $ height = "height"여야합니다. – Parziphal

    +0

    오른쪽, 감사합니다. if (substr ($ match, 0, 5) === $ height)가 ($ match, 0, 6)을 반영해야합니다. – moreyt25

    +0

    정교하게 작성해야 할 수도 있습니다. 무엇으로 무엇을 대체할까요? height = 및 width = numbers를 제거하거나 추가하거나 바꾸시겠습니까? - parseIt 해결 방법은 아주 까다 롭습니다. 당신은 하나의'preg_replace ('/ (width | height) = "\ d +"/', '$ 1 = "200"', $ src)' – mario

    답변

    7

    preg_replace을 사용할 수 있습니다. 일치시키려는 정규 표현식의 배열과 대체 배열을 취할 수 있습니다. width="\d+"height="\d+"을 일치시키고 싶습니다. (임의의 html을 파싱하는 경우 공백을 확장하여 선택 사항 인 공백이나 작은 따옴표와 일치하도록 할 수 있습니다.)

    $newWidth = 285; 
    $newHeight = 175; 
    
    $content = preg_replace(
        array('/width="\d+"/i', '/height="\d+"/i'), 
        array(sprintf('width="%d"', $newWidth), sprintf('height="%d"', $newHeight)), 
        $content); 
    
    +0

    훌륭하고 앞서 언급 한대로 일했습니다. 고마워, 나는 언젠가 좋은 사람이되기를 바랄 뿐이다. – moreyt25

    +0

    CSS % 및 px 값으로이 작업을 수행해야합니다. 이 값 내에서 작동합니까? – Nederealm

    관련 문제