Pedram
Pedram

Reputation: 16575

PHP (preg_replace) remove special character not non-english

I'm trying to remove all special character like

()[]{}~`@#$%^&*_+=/|.,،;:?؟><

but this code will remove all spec character plus non english character, i want only remove spec character not non-english. i means only accept english+non english but not special character.

preg_replace("/[^A-Za-z0-9\-]/", "-", $_REQUEST["title"]);

Upvotes: 1

Views: 1522

Answers (2)

Toto
Toto

Reputation: 91375

Use unicode property:

preg_replace("/[^\p{L}\p{N}]/u", "-", $_REQUEST["title"]);

This will replace any character that is not a letter and not a digit by a dash.

Edit according to comment:

$regex = array('/[^\p{L}\p{N}\s]/u', '/\s/');
$repl  = array('', '-');
preg_replace($regex, $repl, $_REQUEST["title"]);

Upvotes: 1

arkascha
arkascha

Reputation: 42885

As a result of the discussion in the comments this might get you started:

<?php

$subject = "This is a string ()[]{}~`@#\$%^&?؟*_+=/|.,،;:' getting stripped.";

$pattern = sprintf('/[%s]/', preg_quote("()[]{}~`@#$%^&?؟*_+=/|.,،;:'", '/'));
$subject = preg_replace($pattern, '', $subject);

echo $subject."\n";

About the sql injection prevention you also mentioned: as said in the comments to the question you have to use a modern database adapter (mysqli or PDO) and "prepared statements". You will find an explanation about that in the documentation. Everything else is "fixing the problem only a bit" which does not make sense at all.

Upvotes: 1

Related Questions