PHP mb_ereg_replace not replacing while preg_replace works as intended

£可爱£侵袭症+ 提交于 2019-12-01 20:11:24

问题


I am trying to replace in a string all non word characters with empty string expect for spaces and the put together all multiple spaces as one single space.

Following code does this.

$cleanedString = preg_replace('/[^\w]/', ' ', $name);  
$cleanedString = preg_replace('/\s+/', ' ', $cleanedString);

But when I am trying to use mb_ereg_replace nothing happens.

$cleanedString = mb_ereg_replace('/[^\w]/', ' ', $name);  
$cleanedString = mb_ereg_replace('/\s+/', ' ', $cleanedString);

$cleanedString is same as of that if $name in the above case. What am I doing wrong?


回答1:


mb_ereg_replace doesn't use separators. You may or may not also have to specify the encoding before.

mb_regex_encoding("UTF-8");
//regex could also be \W
$cleanedString = mb_ereg_replace('[^\w]', ' ', $name);
$cleanedString = mb_ereg_replace('\s+', ' ', $cleanedString);



回答2:


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; 

}

please check is it ok and support english and unicode




回答3:


The input is not Multi-Byte hence the mb function fails.



来源:https://stackoverflow.com/questions/3594627/php-mb-ereg-replace-not-replacing-while-preg-replace-works-as-intended

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!