douhezi2285 2017-09-24 08:37
浏览 28
已采纳

在PHP中使用preg_match的UTF正则表达式

I need a regeular expression for german words with ä,ü etc.

When I test this regex on this website https://regex101.com/

/^\p{L}+$/u

all is fine, but on my server I upload a CSV and want to parse the words. When I call with the word "Benedikt"

preg_match("/^[\p{L}]+$/u", $attributes[0])

I get false. The encoding of the CSV is UTF-8, when I convert it to ANSI, all is good but the ä,ü etc. is not shown correctly, so I think I should convert it to UTF-8. But why is it returning false?

  • 写回答

2条回答 默认 最新

  • douyong6585 2017-09-24 18:23
    关注

    The problem occurs because your csv file starts with a UTF-8 BOM. If you remove this, the regex works perfectly. I have confirmed it with this code:

    <html>
    <head>
    <meta charset="utf-8" /> 
    </head>
    <body>
    <?php
    function remove_utf8_bom($text)
    {
        $bom = pack('H*','EFBBBF');
        $text = preg_replace("/^$bom/", '', $text);
        return $text;
    }
    
    $csvContents = remove_utf8_bom(file_get_contents('udfser_new.csv'));
    $lines = str_getcsv($csvContents, "
    "); //parse the rows
    
    foreach ($lines as &$row) {
        $row = str_getcsv($row, ";");
    
        $firstName = $row[0];
        $lastName = $row[1];
        echo 'First name: ' . $firstName . ' - Matches regex: ' . (preg_match("/^[\p{L}]+$/u", $firstName) ? 'yes' : 'no') . '<br>';
        echo 'Last name: ' . $lastName . ' - Matches regex: ' . (preg_match("/^[\p{L}]+$/u", $lastName) ? 'yes' : 'no') . '<br>';
    }
    ?>
    </body>
    </html>
    

    The regex match the text successfully, and the ü in Glückmann is shown correctly on the page.

    Result

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 spring后端vue前端
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题