我在 this 中找到site 提供了一个非常基本的 javascript 函数来对文本进行编码。查看源代码这是字符串替换代码:
txtEscape = txtEscape.replace(/%/g,'@');
所以字符串stackoverflow
变成@73@74@61@63@6B@6F@76@65@72@66@6C@6F@77
我需要一个在 php 中执行相同基本加密的函数,但我真的不明白 /%/g
是什么意思。做。我认为在 php 中相同的函数会是这样的:
str_replace(/%/g,"@","stackoverflow");
当然是/%/g
不起作用
最佳答案
替换字符
确实,PHP函数是str_replace
(用于替换的函数有很多)。但是,regex
表达式并不相同:)
查看官方文档:http://php.net/manual/en/function.str-replace.php
就您而言,您希望将字母 %
替换为 @
。
g
是一个正则表达式标志。和 //
是激活正则表达式模式的分隔符:)
The "g" flag indicates that the regular expression should be tested against all possible matches in a string. Without the g flag, it'll only test for the first.
<?php
echo str_replace('%', '@', '%73%74%61%63%6B%6F%76%65%72%66%6C%6F%77');
?>
在 PHP 中,您可以将标志与正则表达式一起使用:preg_replace
和 cie。
逃脱
查看这篇文章:PHP equivalent for javascript escape/unescape
有两个函数 stringToHex
和 hexToString
可以完成您想要的操作:)
事实上,您提供的网站使用espace
函数来编码消息:
document.write(unescape(str.replace(/@/g,'%')));
关于javascript - 将 javascript 字符串替换函数转换为 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42029059/