PHP or Javascript: Simply Remove and Replace HTML Code

二次信任 提交于 2020-01-06 03:11:13

问题


I have this code on my page, but the link has different names and ids:

   <div class="myclass">
    <a href="http://www.example.com/?vstid=00575000&amp;veranstaltung=http://www.example.com/page.html">
Example Text</a>
    </div>

how can I remove and Replace it to this:

<div class="myclass">Sorry no link</div>

With PHP or Javascript? I tried it with str.replace

Thank you!


回答1:


I assume you mean dynamically? You won't be able to do this with php because it is server side, and doesn't have anything to do with the HTML once its been output to the screen.

See: http://www.tizag.com/javascriptT/javascript-innerHTML.php for the javascript.

Or you could use jquery which is just better and nicer than trying to do a cross browser compatible javascript script.

$('.myclass').html('Sorry...');




回答2:


If the page is still on the server before you need to make the replacement, do this:

<?php if (allowed_to_see_link()) { ?>
<div class="myclass">
<a href="http://www.example.com/?   vstid=00575000&amp;veranstaltung=http://www.example.com/page.html">
 Example Text</a>
</div>
<?php } else { ?>
non-link-text
 <php } ?>

and also write the named functions...




回答3:


You might want to clearify what you are up to. If that is your file, then you can simply open up in an editor and remove the portions. If you want to modify HTML with PHP, you can use native DOM

$dom = new DOMDocument;
$dom->loadHTML($htmlString);
$xPath = new DOMXPath($dom);
foreach( $xPath->query('//div[@class="myclass"]/a') as $link) {
    $link->parentNode->replaceChild(new DOMText('Sorry no link'), $link);
}
echo $dom->saveHTML();

The above code would replace any direct <a> element children of any <div> elements that have a class attribute of myclass with the Textnode "Sorry no link".



来源:https://stackoverflow.com/questions/3555597/php-or-javascript-simply-remove-and-replace-html-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!