2017-12-30 6 views
2

"index.html"파일의 문자열을 대체하는 코드에서 작업 중이며 HTML 태그 안에 반복되는 문자열이 있습니다. l. 나는 다른PHP를 사용하여 HTML 태그 안에 반복되는 내용의 특정 내용을 ID를 사용하여 대체하십시오.

문제로 문자열을 대체하기 위해 PHP를 사용하고 문자열 많은 태그 반복 될 수 그래서이 PHP 코드를 대체하기 때문에, 특정 ID로 태그 내부에 PHP 코드 변경 문자열을 만드는 방법 파일

$(document).ready(function() { 
 
    $("p").click(function() { 
 
     var mid= this.id; 
 
     var yyy = document.getElementById(mid).innerHTML; 
 
     document.getElementById("oldvalue").value = yyy; 
 
     document.getElementById("iddddd").value=mid; 
 
     document.getElementById("newvalue").value ="text2" 
 
    }); 
 
});
<p id="parg1" >text1 </p> 
 
<p id="parg2">text1 </p> 
 
<form action="changeText.php" method="POST" > 
 
    <input type="hidden" id="oldvalue" name="oldvalue" class="inputText"> 
 
    <input type="hidden" id="newvalue" name="newvalue" class="inputText" > 
 
    <input type="hidden" id="iddddd" name="id" class="inputText"> 
 

 
    <input type="submit" id="submitbutton" value="Save" > 
 
</form>

// PHP 코드

,536 내부의 모든 문자열
$content=file_get_contents("index.html"); 
$content_chunks=explode($_POST['oldvalue'], $content); 
$content=implode($_POST['newvalue'], $content_chunks); 
file_put_contents("index.html", $content); 
//result from that is 
//<p id="parg1" >text2 </p> 
//<p id="parg2">text2 </p> 

답변

1

이 경우 DOMDocument을 사용해야합니다. 자세한 내용은 php docs에서 확인하십시오.

여기에 간단한 예제 :

<?php 
function replaceByID(String $html,String $id,String $search,String $replace) : String 
{ 
$dom = new \DOMDocument(); 
$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); 

$element = $dom->getElementByID($id); 
$element->nodeValue = str_replace($search,$replace,$element->nodeValue); 

$html = $dom->saveHTML(); 
return $html; 
} 



$file = 'index.html'; 
$html = file_get_contents($file); 
$oldText = htmlspecialchars($_POST['oldValue']); 
$newText = htmlspecialchars($_POST['newValue']); 
$html = replaceByID($html,'parg1',$oldText,$newText); 

편집 :

난 그냥이 기능을 테스트하고 완벽하게 작동, 난 당신을 위해 일을 얻을 수있는 것 같아요.

HTML 파일을 조작하거나 편집해야하는 프로젝트에서 작업하는 경우 DOMPHP DOM에 대해 자세히 알아볼 것을 적극 권장합니다. 당신이 을 @azjezz에 대한

+0

큰 덕분에 나는 다시 그들에 대해 곧 감사를 배울 것입니다 그것은 100 % 그냥 "file_put_contents를 ($ 파일, $ html로) "추가 작업 끝에 –

관련 문제