<?php
function toconv(string)
{
$gogo = array("a" => "b","cd" => "e");
$string = str_replace(
array_keys( $gogo ),
array_values( $gogo ),
$string
);
return $string;
}
?>
如何在JavaScript中实现它?
答案 0 :(得分:4)
以某种方式制作它,你可以直接从一个数组中完成它:
<script type="text/javascript">
function toconv(string){
var gogo = {"a":"b", "cd":"e"}, reg;
for(x in gogo) {
reg = new RegExp(x, "g");
string.replace(x, gogo[x]);
}
return string;
}
</script>
答案 1 :(得分:2)
Javascript中的String.replace()接收正则表达式而不是字符串,这里是一个翻译。您需要将g修饰符附加到正则表达式以替换所有出现而不是仅替换第一个出现。
<script>
function toconv(str) {
replacements = ['b','e'];
regexes = [/a/g,/cd/g];
for (i=0; i < regexes.length; i++) {
str = str.replace(regexes[i],replacements[i]);
}
return str;
}
alert(toconv('acdacd'));
alert(toconv('foobar'));
</script>
答案 2 :(得分:-1)
将PHP函数转换为JavaScript
if (preg_match('/0/', $check) || preg_match('/1/', $check) || preg_match('/2/', $check) || preg_match('/3/', $check) || preg_match('/4/', $check) || preg_match('/5/', $check) || preg_match('/6/', $check) || preg_match('/7/', $check) || preg_match('/8/', $check) || preg_match('/9/', $check))
{
exception("personal info not allowed");
redirect(base_url() . 'edit_profile');
}
else if ((preg_match("~\b@\b~",$check)) || (preg_match("~\b.net\b~",$check)) || (preg_match("~\b.com\b~",$check)) || (preg_match("~\b@\b~",$check)) || (preg_match("~\b.edu\b~",$check)) || (preg_match("~\b.gov\b~",$check)))
{
exception("personal info not allowed");
redirect(base_url() . 'edit_profile');
}