Search code examples
phparraysspecial-characters

php if string contains any character from an array


I have an xml document that gets loaded onto a page. Sometimes there are specific characters that cannot be parsed and shows this symbol in place of what should be there: –

Sometimes the character varies from a hyphen, to an apostrophe, to even a double quote.

What I'd like to do is, create an array:

$invalidCharacters = array(" – ", "’", "&");

and if the string contains any of those characters, replace them with their HTML/ASCII equivalent. like this: " – ", "'", and &.

I know that I can do a str_replace() on some items, but, is there a simple way to have it go trough a loop and look for the specific characters, replacing each as it goes?


Solution

  • Using htmlspecialchars should work for you.

    http://docs.php.net/manual/en/function.htmlspecialchars.php