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 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题