2011-02-14 8 views
2

< 코드 내에서 내용에 대해서만 htmlentities()를 실행하고 싶습니다. </코드 ><code></code>에서만 PHP htmlentities!

문자열을 취하여 < 코드 사이의 내용을 찾는 함수를 작성했습니다. > </code >

function parse_code($string) {

  // test the string and find contents with <code></code> 
     preg_match('@<code>(.*?)</code>@s', $string, $matches); 

      // return the match if it succeeded 
      if($matches) { 
       return $matches[1]; 
      }else { 
       return false; 
      } 
    } 

그러나 실제로 htmlentities()를 실행할 함수에 대한 도움이 필요합니다. < 코드 > </코드 > 내의 내용에 다음 implode() 모든 다시 함께. 예를 들어 아래 문자열이 있다고 가정 해 보겠습니다.

 
<div class="myclass" rel="stuff"> things in here </div> 
<code> only run htmlentites() here so strip out things like < > " ' & </code> 
<div> things in here </div> 

다시 한번이 함수는 문자열의 모든 내용을 동일하게 유지해야하지만 < 코드의 내용에 대해 htmlentities() 만 수정하고 실행해야합니다. > </code >

+0

이 글을 읽는 것이 좋습니다 - http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – Phil

+0

@phil ahh very interesting. – kr1zmo

답변

5

당신은이 작업을 단순화 할 수

 
<div class="myclass" rel="stuff"> things in here </div> 
<code> only run htmlentites() here so strip out things like < > " ' & </code> 
<div> things in here </div> 

다시 한번,이 기능은 < 코드의 내용에를 htmlentities()를 같은 문자열의 모든 내용을 유지하지만 수정하고 실행해야합니다 바깥 쪽 코드 태그를 일치하는 구문은 lookbehind and lookahead assertion라고

$html = preg_replace_callback(
    "@ (?<= <code>) .*? (?= </code>) @six", 
    "htmlentities_cb", $html 
); 

function htmlentities_cb($matches) { 
    return htmlentities($matches[0], ENT_QUOTES, "UTF-8"); 
} 

: 사용자 정의 콜백 함수를 사용하여와. 어설 션 자체가 $ matches [0]의 일부가되지 않기 때문에 콜백을 단순화하고 implode()를 나중에 피할 수 있습니다. @six는 case-insensitve 태그 일치를위한 것이지만 정규 표현식의 공백은 더 쉽게 읽을 수 있습니다.

+0

나는 이것을 시험해 볼 것이고, 그것이 효과가 있다면, 당신을 사랑합니다. 당신을 사랑합니다. 당신을 사랑합니다. – kr1zmo

+0

@ kr1zmo : 테스트를 거쳤으나 코드를 사용해 보시기 바랍니다. 또한 더 나은 보안을 위해 추가 htmlentities 매개 변수를 잊지 마세요. – mario

+0

그래서 내 문자열 $ query = ''; 그 모든 HTML 및 코드 태그가 있습니다. – kr1zmo