Toni Latenz
Toni Latenz

Reputation: 216

php preg_replace function wrong result

I am trying to remove (most) special chars from a user given $_POST string, before inserting it into the database, with the following preg_replace function:

preg_replace('/[^a-zA-Z0-9\-._äöü]/', '', $description);

Now, when entering this for $description:

abc !"§$%&/()=?`*'#+´ß

The result is just:

?

Why is the function removing abc, but is keeping the '?', which is not in my whitelist of preg_replace? Any answers are much apreciated.

Upvotes: 1

Views: 271

Answers (3)

Ruslan Osmanov
Ruslan Osmanov

Reputation: 21492

PHP should be configured for UTF-8. Set the default_charset INI option to 'UTF-8'; use the u pattern modifier:

ini_set('default_charset', 'UTF-8');
$description = 'abc !"§$%&/()=?`*\'#+´ß.';
$r = preg_replace('/[^a-zA-Z0-9\-\._äöü]/u', '', $description);
var_dump($r);

Sample output

string(4) "abc."

Also, consider setting a UTF-8 locale, since functions such as basename are locale-aware:

setlocale(LC_ALL,
  'de_DE.UTF-8',
  'de_DE.utf8',
  'en_US.UTF-8',
  'en_US.utf8'
);

Upvotes: 1

user6533277
user6533277

Reputation:

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

How to use :

echo clean('a|"bc!@£de^&$f g');

Upvotes: 0

devpro
devpro

Reputation: 16117

You can use '/\W/' will remove all special characters:

<?php
$string = 'abc !"§$%&/()=?*#+´ß';
echo preg_replace('/\W/', '', $string); // abc
?>

Upvotes: 0

Related Questions