Tutorial :Help with preg_replace and special chars



Question:

I'm using the PDO class but I'm triying to remove all chars except...:

function cleaner($str){      return preg_replace('/[^a-zA-Z0-9éàêïòé\,\.\']/',' ',trim($str));  }  

As you can see, it's a simple function, but it removes all chars éàêïòé

example: cleaner('$#$<<>-//La souris a été mangée par le chat ') //returns

La souris a t mang e par le chat (The mouse has been eaten by the cat :) )

Any help will be appreciate


Solution:1

$str = '$#$<<>-//La souris a été mangée par le chat ';  $str = preg_replace('/[^a-zA-Z0-9éàêïòé\,\.\']/u',' ',trim($str));    $str = '$#$<<>-//La souris a été mangée par le chat ';  $str = preg_replace('/[^\p{L}\,\.\']/u',' ',trim($str));  

Both the snippets worked for me, on PHP 5.3. The second regular expression is less restricted, and accepts all Unicode letters.


Solution:2

You need to add /u pattern modifier to your pattern to turn on UTF-8 support in PCRE. This is assuming everything is in UTF-8 already.

http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »