php
  • regex
  • 2012-07-31 3 views 0 likes 
    0

    모든 div의 containig 클래스 "ta"와 id "ta_somenumber"를 동일한 속성을 유지할 텍스트 영역으로 바꿔야합니다. 나는이 함께 노력했다div를 regex로 바꾸기

    $html_new_content = '<textarea class="ta" id="ta_345">sometext</textarea><span style="...">Some text</span><--!more html--><textarea class="ta" id="ta_5687">sometext</textarea>'; 
    

    :

    여기
    $html_content = '<div class="ta" id="ta_345">sometext</div><span style="...">Some text</span><--!more html--><div class="ta" id="ta_5687">sometext</div>'; 
    

    내가 달성하고자하는 것입니다 :

    $regex1 = '#\<div class=\"ta\" id=\"(.*)\"\>(.+?)\<\/div\>#s'; 
    $regex2 = '#\<textarea class=\"ta\" id=\"(.*)\"\>(.+?)\<\/textarea\>#s'; 
    
    $result = str_replace($regex2, $regex3, $html_content); 
    

    을하지만 어떤 이유로이 나던 작업을 위해 다음 예제 코드이다. 나는 preg_replace로 시도했지만 운은 없었습니다.

    +1

    HTML은 정규 언어가 아니므로 정규식을 사용하여 HTML을 구문 분석하는 것은 좋지 않습니다. http://stackoverflow.com/questions/590747/using-regular-expressions-to-parse-html-why-not – Matt

    답변

    2

    당신은 하나의 정규식을해야하고, 그 같을 것이다 :

    $regex = '#<div class="ta" id="([^"]+)">(.+?)</div>#s'; 
    $result = preg_replace($regex, 
        '<textarea class="ta" id="$1">$2</textarea>', 
        $html_content 
    ); 
    

    이것은 <div> 모든 태그를 발견, 자신의 ID를 캡처하는 것은 역 참조 # 1 속성 및 역 참조 # 2에서 자신의 콘텐츠. 그런 다음 교체는 간단합니다. <div><textarea>으로 대체하고 "ta"클래스와 동일한 ID 및 내용을 원본 <div>과 동일하게 만드십시오.

    the demo에서 작동하는 것을 볼 수 있습니다.

    +0

    'class'와 'id' 속성이 항상 같은 방식으로 정렬 된 경우에만 a @@SoneoneS : 당신은 나무/DOM을 생성하고 속성을 변경해야합니다. – amon

    관련 문제