如何在PHP中替换字符串中的非ASCII字符? [英] How to replace non-ASCII characters in a string in PHP?

查看:378
本文介绍了如何在PHP中替换字符串中的非ASCII字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的字符串是这样的

  $ inputText =centralkøkkenetkliniskediætister; 

在那个字符串中有像øæ即可。这些字符应该被替换。如何在一个正则表达式中提及这些可用于替换的正则表达式?如果您要替换除字母数字以外的其他所有字符然后试试它。

  [^ a-zA-Z0-9] 

以下是演示 a>

示例代码:

  $ re =/ ^ a-zA-Z0-9] /; 
$ str =centralkøkkenetkliniskediætister;
$ subst ='';

$ result = preg_replace($ re,$ subst,$ str);






更好地使用 [^ \ w \s] [\W\S] ,使其简短,如@ hjpotter92所示。

模式解释:

  [^ \ w \\ \\ s]除以下字符外的任何字符:
(az,AZ,0-9,_),空格(\ n,\ r,\ t,\f和)

[\W\S]任何字符:
非单词字符(除az,AZ,0-9,_之外的所有字符),
非空白字符\\\
,\r,\t,\f和)


I need to replace characters in a string which are not represented with a single byte.

My string is like this

$inputText="centralkøkkenet kliniske diætister"; 

In that string there are characters like ø and æ. These characters should be replaced. How do I mention these in a regular expression that I can use for replacement?

解决方案

If you want to replace everything other than alphanumeric and space character then try it.

[^a-zA-Z0-9 ]

Here is demo

Sample code:

$re = "/[^a-zA-Z0-9 ]/";
$str = "centralkøkkenet kliniske diætister";
$subst = '';

$result = preg_replace($re, $subst, $str);


Better use [^\w\s] or [\W\S] to make it short and simple as suggested by @hjpotter92 as well in comments.

Pattern explanation:

[^\w\s]                any character except: word characters:
                        (a-z, A-Z, 0-9, _), whitespace (\n, \r, \t,\f, and " ")

[\W\S]                 any character of: 
                         non-word characters (all but a-z, A-Z, 0-9, _), 
                         non-whitespace (all but \n, \r, \t, \f, and " ")

这篇关于如何在PHP中替换字符串中的非ASCII字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆