dsqa6272 2014-03-26 11:05 采纳率: 0%
浏览 80
已采纳

如何用preg_replace和PHP替换特殊字符?

Let say we have random string like this:

$str_test = "faafŠ š čćž đš čšđ ćčš žž fa fssfa afž afžsa f";

and we do some preg_replace function on it:

preg_replace("/[^\da-z ]/i", "_", $str_test);

And the result I get is:

faaf__ __ ______ ____ ______ ______ ____ fa fssfa af__ af__sa f

So if we compare bothe - input and output:

faaf__ __ ______ ____ ______ ______ ____ fa fssfa af__ af__sa f
faafŠ š čćž đš čšđ ćčš žž fa fssfa afž afžsa f

we can see that all special chars are being replaced with two signt "_" ... Result should be:

faaf_ _ ___ __ ___ ___ __ fa fssfa af_ af_sa f
faafŠ š čćž đš čšđ ćčš žž fa fssfa afž afžsa f

I have tried with encodings already but no success.. I also thought to make function to do multiple preg_match once and than replace "_" with "" ... but that would be slow on big texts ...

Any Ideas?

  • 写回答

2条回答 默认 最新

  • duanha3539 2014-03-26 11:32
    关注
    $str=preg_replace("/[^0-9a-zA-Z ]/u", "_", $str_test);
    

    Notice 'u' modifier! Explanation: http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php#107498

    If the _subject_ contains utf-8 sequences the 'u' modifier should be set, otherwise a pattern such as /./ could match a utf-8 *sequence as two to four individual ASCII characters*.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化