简体   繁体   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>

I'm trying to regex the value from the input. 我正在尝试从输入中复制值。
Unfortunately, every time I submit the characters, preg_match return false . 不幸的是,每次提交字符时, preg_match返回false But, if I use the string from the variable, it'll return true . 但是,如果我使用变量中的字符串,它将返回true

What going on and how do I fix it? 发生了什么,我该如何解决?

If anyone ran into this problem, I've found it. 如果有人遇到这个问题,我已经找到了。 You just need to add this meta header: 您只需要添加此元标头:

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

I'm not sure why, but with out the codes above, html it send the values to php as a non-utf-8 value. 我不知道为什么,但是没有上面的代码,html它将值作为非utf-8值发送给php。 So, then the preg_match try to read it, its reading a different value then what was typed in, thus; 所以,然后preg_match尝试读取它,它读取的值与输入的值不同,因此; it return false. 它返回false。

That's why it work when you just uses the string. 这就是你只使用字符串时它的工作原理。 HTml is not involved. HTml不参与。

note. 注意。 Even if you try to read by echoing it out, html with return it to its orginal utf-8 value. 即使您尝试通过回显它来阅读,html也会将其恢复为原始的utf-8值。 weird. 奇怪的。

Example: 例:

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