简体   繁体   English

如何查看 JavaScript / PHP 中的 2 段代码是否等效?

[英]How can I see if 2 pieces of code are equivalent in JavaScript / PHP?

I have some Ajaxing going on and I have 2 blocks of source code.我有一些 Ajaxing 正在进行,我有 2 块源代码。 The first is:第一个是:

window.lastSavedContents = "<?php echo htmlentities( $contents ); ?>";

The second is whatever the user types into a text editor.第二个是用户在文本编辑器中输入的任何内容。 The problem is window.lastSavedContents is htmlentities encoded, whereas the second block is not.问题是window.lastSavedContentshtmlentities编码的,而第二个块不是。

How can I check for equivalence?如何检查等效性?

First, don't use htmlentities , but htmlspecialchars , that only encodes < , > , & and " . That way, you can simply replace those entities using首先,不要使用htmlentities ,而是使用htmlspecialchars ,它只编码<>&" 。这样,您可以简单地使用替换这些实体

var decoded = encoded.replace(/&amp;/g, '&')
                     .replace(/&lt;/g, '<')
                     .replace(/&quot;/g, '"')
                     .replace(/&gt;/g, '>');

If you still want to use htmlentities you can simply create a temporary div :如果您仍想使用htmlentities ,您可以简单地创建一个临时div

var div = document.createElement('div');
div.innerHTML = encoded;
var decoded = div.firstChild.nodeValue;

You could either find a way around entity encoding the data, or decode window.lastSavedContents in Javascript.您可以找到一种绕过实体编码数据的方法,或者在 Javascript 中解码window.lastSavedContents Here's a function that will help you do that: http://phpjs.org/functions/html_entity_decode:424这是一个 function 可以帮助您做到这一点: http://phpjs.org/functions/html_entity_decode:424

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM