简体   繁体   English

如何使用php修改脚本的输出?

[英]How do I modify the output of a script with php?

Maybe it's a stupid question but I have this script: 也许这是一个愚蠢的问题,但是我有这个脚本:

<script language="javascript">
document.write('<a class="white-link" href="?s=' + geoip_city() + '">¿Estás en ' + geoip_city() +'?</a>');
</script>

and I simply want to remove accents of all characters of "geoip_city()" using strtr. 并且我只想使用strtr删除“ geoip_city()”所有字符的重音。 Normally I know how to do it but I'm not very sure this time since it's a script. 通常我知道该怎么做,但是这次我不是很确定,因为它是脚本。 I always use this to remove the accents: 我总是用它来去除口音:

<?php
$text = "    ";
$trans = array("á" => "a", "é" => "e", "í" => "i", "ó" => "o", "ú" => "u");
echo strtr($text, $trans);
?>

How do I do it? 我该怎么做?

If it's not clear please ask. 如果不清楚,请询问。

Thanks a lot 非常感谢

You'll need to reimplement (at least a basic version) the strtr PHP function in javascript. 您需要在JavaScript中重新实现(至少是基本版本) strtr PHP函数。 The function is fairly simple, you accept a translation table that maps original to new, then replace all instances of the original values with their respective new values. 该函数非常简单,您接受一个将原始映射到新映射的转换表,然后将原始值的所有实例替换为其各自的新值。

function trans(text, table) {
    for(var i = 0; i < table.length; i++) {
        var entry = table[i];
        text = text.replace(new RegExp(entry[0], 'g'), entry[1]);
    }

    return text;
}

You can use it directly like so: 您可以像这样直接使用它:

var $trans = [
    ['a','b'],
    ['c','d']
];

alert(trans('acdc cats pajamas', $trans));

Like I said, the trans function is fairly simple. 就像我说的, trans函数非常简单。 It iterates over every entry in the supplied translation table, and turns the first element in the entry into a regular expression. 迭代提供的转换表中的每个条目,并将条目中的第一个元素转换为正则表达式。 The reason it turns it into a regular expression (using new RegExp ) is because of the 'g' option, which allows you to replace every match, instead of just the first one found. 之所以将其转换为正则表达式(使用new RegExp )的原因是由于使用了'g'选项,该选项使您可以替换每个匹配项,而不仅仅是找到的第一个匹配项。

And an example way to use it in your exact circumstance: 以及在实际情况下使用它的示例方法:

<script>
function trans(text, table) {
    for(var i = 0; i < table.length; i++) {
        var entry = table[i];
        text = text.replace(new RegExp(entry[0], 'g'), entry[1]);
    }

    return text;
}

var trans_table = [
    ["á", "a"],
    ["é", "e"],
    ["í", "i"],
    ["ó", "o"],
    ["ú", "u"]
];

var geoip_city_trans = trans(geoip_city(), trans_table);

document.write('<a class="white-link" href="?s=' + geoip_city_trans + '">¿Estás en ' + geoip_city_trans +'?</a>');

</script>

Note : I would suggest having the translation table and the actual trans function in an external script that's included into this page, versus defining it where you want to print the anchor. 注意 :我建议在此页面包含的外部脚本中使用转换表和实际的trans函数,而不是在要打印锚点的位置定义它。

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

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