douqiong8412 2017-12-30 18:17
浏览 61
已采纳

使用PHP使用ID替换HTML标记内的重复内容中的某些内容

I'm working on code that replaces strings in "index.html" file and there is a repeated string inside HTML tags l. I'm using PHP to replace string with another one

The problem is that string may be repeated in many tags so how to make PHP code change string inside tags with certain id, because this PHP code replace all strings inside file

$(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 code

$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>
</div>
  • 写回答

1条回答 默认 最新

  • dongtiao0657 2017-12-30 19:09
    关注

    You need to use DOMDocument for this you can read more about it at the php docs.

    here's a simple example :

    <?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 :

    I just tested this function and it works perfectly , i guess it can get the job done for you.

    If you are working on a project where you need to manipulate or edit HTML files i highly recommend you learn about DOM and PHP DOM .

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题