PHP mb_ereg_替换未替换,而preg_替换按预期工作
我试图用空字符串替换字符串中的所有非单词字符(空格除外),并将所有多个空格合并为一个空格 下面的代码实现了这一点PHP mb_ereg_替换未替换,而preg_替换按预期工作,php,regex,pcre,multibyte,Php,Regex,Pcre,Multibyte,我试图用空字符串替换字符串中的所有非单词字符(空格除外),并将所有多个空格合并为一个空格 下面的代码实现了这一点 $cleanedString = preg_replace('/[^\w]/', ' ', $name); $cleanedString = preg_replace('/\s+/', ' ', $cleanedString); 但是当我尝试使用mb_ereg_替换时,什么都没有发生 $cleanedString = mb_ereg_replace('/[^\w]/', ' '
$cleanedString = preg_replace('/[^\w]/', ' ', $name);
$cleanedString = preg_replace('/\s+/', ' ', $cleanedString);
但是当我尝试使用mb_ereg_替换时,什么都没有发生
$cleanedString = mb_ereg_replace('/[^\w]/', ' ', $name);
$cleanedString = mb_ereg_replace('/\s+/', ' ', $cleanedString);
$cleanedString与上述情况下的if$name相同。我做错了什么?输入不正确,因此
mb
功能失败。mb\u ereg\u replace
不使用分隔符。在此之前,您可能需要指定编码,也可能不需要指定编码
mb_regex_encoding("UTF-8");
//regex could also be \W
$cleanedString = mb_ereg_replace('[^\w]', ' ', $name);
$cleanedString = mb_ereg_replace('\s+', ' ', $cleanedString);
}
请检查它是否正常并支持英语和unicode正常。但是,如果我的输入是UTF-8格式的,您能解释一下我们什么时候应该使用mb_ereg_替换而不是preg_替换吗。目前我将英文文本作为$name传递。但如果明天我用其他语言说印地语,我的密码会被破解吗?错。多字节扩展可以处理单字节编码。谢谢,这是我犯的错误。如果我的输入是UTF-8,是否有关于使用哪种方法的建议?@Jithin如果是UTF-8,您最好使用
preg\u replace
和u
标志:preg\u replace('/\s+/u','.$cleanedString)代码>@谢谢。你能告诉我,只要输入是UTF-8编码,preg_替换就可以适用于大多数语言吗?@Jithin取决于你对“works”的理解。它将在严格意义上工作——不会生成损坏的数据,但它可能无法满足您的需要。考虑第一个正则表达式。在PCRE(发动机preg\u replace
使用)中,\w
仅表示[a-zA-Z0-9]
。如果要消除所有非单词字符,更好的选择是使用[^\p{L}\p{Nd}\p{Mn}}
。这将匹配所有非(按Unicode)字母、非间隔标记(用于重音符号等)、十进制数字和下划线的字符。@Jithin否。它使用。默认情况下,\w
表示(字母|标记|数字|连接器|标点符号)。虽然只回答代码是不被禁止的,但请理解这是一个问答社区,而不是一个众包社区,通常,如果OP理解作为答案发布的代码,他/她会自己想出类似的解决方案,一开始就不会提出问题。因此,请通过解释答案和/或代码的工作方式和/或原因,为答案和/或代码提供上下文。
function create_slug_html($string, $ext='.html'){
$replace = '-';
$string=strtolower($string);
$string=trim($string);
mb_regex_encoding("UTF-8");
//regex could also be \W
$string= mb_ereg_replace('[^\w]', ' ', $string);
$string= mb_ereg_replace('\s+', ' ', $string);
//remove query string
if(preg_match("#^http(s)?://[a-z0-9-_.]+\.[a-z]{2,4}#i",$string)){
$parsed_url = parse_url($string);
$string = $parsed_url['host'].' '.$parsed_url['path'];
//if want to add scheme eg. http, https than uncomment next line
//$string = $parsed_url['scheme'].' '.$string;
}
//replace / and . with white space
$string = preg_replace("/[\/\.]/", " ", $string);
// $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
//remove multiple dashes or whitespaces
$string = preg_replace("/[\s-]+/", " ", $string);
//convert whitespaces and underscore to $replace
$string = preg_replace("/[\s_]/", $replace, $string);
//limit the slug size
$string = substr($string, 0, 200);
//slug is generated
return ($ext) ? $string.$ext : $string;