如果包含 Unicode 字符,则无法在 JavaScript 中解码 PHP 中的编码字符串

我正在尝试使用类似于 Rot13 的算法在 PHP 中对字符串进行编码,然后在 JavaScript 中对字符串进行解码并进行搜索和替换。它适用于 ASCII 字符,但不适用于 Unicode。


我弄乱了附加的代码,但无法让它工作。


<?php


function strRot($str, $n) {

    $len = mb_strlen($str);

    $min = 0;

    $max = 99999999;

    $final = '';


    for ($i = 0; $i < $len; $i++) {

        $current = mb_ord($str[$i]);

        $val = $current+$n;


        if ($val >= $max) {

            $val = $val - $max;

        }


        if ($val <= $min) {

            $val = $val + $min;

        }


        $final .= mb_chr($val);

    }


    return $final;

}


?><!doctype html>

<html>

<head>

    <!-- Required meta tags -->

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">


    <!-- Bootstrap CSS -->

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">


    <title>Hello, world!</title>

</head>

<body>

    <h1>Hello, world!</h1>

    <h2>Ü and ?. 棕色的狐狸跳了起来.</h2>


    <p>The Hello, world! expression will be replaced.</p>

    <p>Ü and ?. 棕色的狐狸跳了起来. Should be replaced too.</p>


    <!-- Optional JavaScript -->

    <!-- jQuery first, then Popper.js, then Bootstrap JS -->

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>

    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>


一旦 JS 运行,它应该用解码后的数据 [索引][1] 替换数据 [索引][0]。


手掌心
浏览 120回答 2
2回答

Helenr

我发现的一种解决方案:var data = [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ["Hello, world!", "<?php echo base64_encode(strRot(rawurlencode('I got replaced.'), 1000)); ?>"],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ["Ü and ?. 棕色的狐狸跳了起来.", "<?php echo base64_encode(strRot(rawurlencode('? before Ü and 棕色的.'), 1000)); ?>"]&nbsp; &nbsp; &nbsp; &nbsp; ];// Then, in replace():decodeURIComponent(strRot(b64DecodeUnicode(data[index][1]), -1000))这是有效的,因为它在旋转之前转义了所有 unicode 字符。唯一的问题是,由于转义,当涉及到字符串的大小时,它会增加一些开销。

蓝山帝景

(我没有足够的声誉来发表评论,所以我求助于使用答案......)不确定它是否有所不同,但在 HTML“h2”标题中,您的 Unicode 表达式是...Ü&nbsp;an&nbsp;?.&nbsp;棕色的狐狸跳了起来....在数据[]中,它是...Ü&nbsp;and&nbsp;?.&nbsp;棕色的狐狸跳了起来.假设“an”和“and”应该是一样的?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript