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尝试读取它,它读取的值与键入的值不同,因此;它返回假。

这就是为什么当你只使用字符串时它会起作用。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>