Monday, February 17, 2014

Removing special Characters from string


Here the following case how to remove special characters easily in a string using preg_replace.

function clean($string) {
   $string = str_replace('', '-', $string); // Replaces all spaces with hyphens.
   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

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


Another example

$string = '<div>This..</div> <a>is<a/> <strong>hello</strong> <i>world</i> ! هذا هو مرحبا العالم! !@#$%^&&**(*)<>?:";p[]"/.,\|`~1@#$%^&^&*(()908978867564564534423412313`1`` "Arabic Text نص عربي test 123 و,.m,............ ~~~ ٍ،]ٍْ}~ِ]ٍ}"; ';
echo preg_replace('/[^A-Za-z0-9 !@#$%^&*().]/u','', strip_tags($string));


Will output: This.. is hello world !    ! 
!@#$%^&&**(*)p.1@#$%^&^&*(()9089788675645645344234123131
 Arabic Text   test 123 .m............