开发者

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

开发者 https://www.devze.com 2023-02-02 12:29 出处:网络
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_c

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. 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. 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. 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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消