繁体   English   中英

utf-8字符输入无法使用PHP正则表达式

[英]utf-8 character input fail to PHP regex

  <?php
        if(isset($_GET['textvalue'])){
            $string = $_GET['textvalue']; //preg_match return false
            //$string = '한자漢字メ'; //preg_match return true
            $stringArray = preg_match('/^[\p{L}]{2,30}$/u', $string);
        }

    ?>



<!DOCTYPE html>
<html>
    <body>
        <form method="GET">
            <input type="text" name="textvalue">
            <input type="submit">
        </form>
    </body>
</html>

我正在尝试从输入中复制值。
不幸的是,每次提交字符时, preg_match返回false 但是,如果我使用变量中的字符串,它将返回true

发生了什么,我该如何解决?

如果有人遇到这个问题,我已经找到了。 您只需要添加此元标头:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

我不知道为什么,但是没有上面的代码,html它将值作为非utf-8值发送给php。 所以,然后preg_match尝试读取它,它读取的值与输入的值不同,因此; 它返回false。

这就是你只使用字符串时它的工作原理。 HTml不参与。

注意。 即使您尝试通过回显它来阅读,html也会将其恢复为原始的utf-8值。 奇怪的。

例:

<?php
if(isset($_GET['textvalue'])){
    $string = $_GET['textvalue']; //preg_match return false
    //$string = '한자漢字メ'; //preg_match return true
    $stringArray = preg_match('/^[\p{L}]{2,30}$/u', $string);
}    
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <head>
    <body>
        <form method="GET">
            <input type="text" name="textvalue">
            <input type="submit">
        </form>
    </body>
</html>

暂无
暂无

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

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