Efficient Strip Special Characters I have a private function in PHP that takes a given URL string and just leave the Alpha or numeric and certain punctuation left. I need the stripping of string due to having it match against ElasticSearch and ElasticSearch doesn't take it too kindly for special characters when it comes to exact match.

The following function so far is working fine.

protected function stripSpecialCharater($string)
{
    $string = iconv("Windows-1252","UTF-8",urldecode($string));
    $string = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $string);
    return preg_replace('/[^a-zA-Z0-9Ã§&amp;-©‚Âƒâ€˜\s]/', '', $string);
}


Can it be better? is there a lib that does this better? I've used Laravel Validation service where you can specify alpha_dash but this is not for validation but rather I need the left over to see if there is a match to the Database Storage for a search.
Regex101.com seems to think you can simply combine \s{2,} and [\t\n] into \s{2,}[\t\n] and it should have the same effect:


$string = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $string);



into:

$string = preg_replace('/\s{2,}[\t\n]/', ' ', $string);




You should add whitespace between your binary operators in this line:


$string = iconv("Windows-1252","UTF-8",urldecode($string));



into:

$string = iconv("Windows-1252", "UTF-8", urldecode($string));


(I'm not personally familiar with iconv, so I can't give too much of a review on your usage of the function.)



Your third regex could be slimmed down from a-zA-Z into a-z with an case insensitive search.


return preg_replace('/[^a-zA-Z0-9Ã§&amp;-©‚Âƒâ€˜\s]/', '', $string);



return preg_replace('/[^a-z0-9Ã§&amp;-©‚Âƒâ€˜\s]/i', '', $string);




In the same way you use a preg_replace with an array, you combine the first pair, with the secondary statement into one line if you like.