2017-12-30 31 views
2

"index.html"ファイル内の文字列を置き換えるコードに取り組んでいます。 私は、問題は、このPHPコードは交換するための文字列は、特定のIDを持つタグ内にPHPコード変更文字列を作成するので、どのように多くのタグで繰り返してもよいことある別の1PHPを使用してHTMLタグ内の繰り返しコンテンツの特定のコンテンツを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コード

内のすべての文字列
$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); 

EDIT:

私はちょうどこの機能をテストし、それが完璧に動作が、私はそれはあなたのために仕事を得ることができますね。

HTMLファイルの操作や編集が必要なプロジェクトで作業している場合は、DOMPHP DOMについて学ぶことを強くおすすめします。

+0

ビッグおかげであなたは を@azjezzために、私は再びそれについてすぐに 感謝を学びます それは100%を働いただけ「ますfile_put_contents($ファイル、$ htmlのを); 」追加終わり –

関連する問題