Skip to content
Advertisement

PHP Cleaning special characters from string

so I made this scraper and it returns strings from multiple sites. I want to check if the strings match, so I use php to clean the string and check. However, the & and other special characters appear in 2 ways, one as & and the other as &. How do I go about removing each type.

preg_replace("/[^a-zA-Z0-9]+/", "", $string);

I already have that, but that doesn’t take out the special characters.

Thanks.

Advertisement

Answer

Try this

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

echo removeSpecialChar(html_entity_decode('&khawer&')); //will output khawer
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement