我为我的客户创建了一个简单的 jquery 插件,该插件获取他的 HTML 文件,并允许他单击某个区域并替换其 HTML 内容。
例如,点击一个div,会提示他一个表单来输入新的文本。当单击“确定”时,它将发送带有他单击的 div 的 HTML 代码的 ajax 请求。
在 PHP 中,我将检查从 Ajax 发送的所有标记,我想用不同的文本替换它们,然后保存新创建的 HTML 文件。
假设我得到了:
<h1>Welcome to my Website!</h1>
我想将其更改为他之前指定的任何内容,
所以
<h1>Welcome to my Website!</h1>
将通过 PHP 更改为
<h2>Hello World!</h1>
在 PHP 中:
<?Php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// get an edited file
$page = file_get_contents("page.html"));
$links = json_decode($_GET['links'], true);
foreach($links as $link) {
$page = str_replace($link['tag'], $link['new_tag'], $page);
}
file_put_contents("test.html", $page);
print 'DONE';
但有时 str_replace 不会替换标签,即使通过查看接受的数组,一切都与 page.html 中存储的内容相同。
======================
编辑
$_GET['link'] 的示例
array(2) {
[0]=>
array(3) {
["tag"]=>
string(28) "<h1>Welcome to Example!</h1>"
["tag_modified"]=>
string(146) "<h1 class="highlighted" onclick="location.href = 'http://www.example.com'">Welcome to Example!.</h1>"
}
[1]=>
array(3) {
["tag"]=>
string(179) "<p>Some Random Text.</p>"
["tag_modified"]=>
string(293) "<p class="highlighted" onclick="location.href = 'http://www.example.com/'">Some Random Text.</p>"
}
}
谢谢。
最佳答案
不要使用 str_replace
函数,而是尝试使用 preg_replace
函数。 http://php.net/manual/en/function.preg-replace.php此链接可能会有所帮助。
关于javascript - 将文本替换为 HTML 文件中的 html 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30894419/