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

报告相同问题?

悬赏问题

  • ¥30 求给定范围的全体素数p的(p-2)的连乘积
  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页