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条)

报告相同问题?

悬赏问题

  • ¥15 怎么制作一个人脸识别门禁系统
  • ¥20 大华dss监控平台网络关闭登不进去
  • ¥15 请使用蚁群算法解决下列问题,并给出我完整的代码
  • ¥20 关于php录入完成后,批量更新数据库
  • ¥15 请教往复密封润滑问题
  • ¥15 cocos creator发布ios包
  • ¥15 comsol压电材料数据
  • ¥35 用python实现除法算法中goldschmidt算法
  • ¥15 汇编代码转换成C代码
  • ¥15 除法算法中的归一化具体是怎么变的?