Well, your array already has the perfect format to use with preg_replace()
.
Substitution can easily be done by looping over your array and calling preg_replace()
once for every set of chars like this:
foreach( $foreign_characters as $replace => $with )
{
$string = preg_replace($replace, $with, $string);
}
Thats basically all you need.
To make things more convenient and easy to use, have a look at this replacement class:
class Replacer
{
/**
* List of character replacements
*/
static $foreign_characters = array(
'/ä|æ|ǽ/' => 'ae',
'/ö|œ/' => 'oe',
'/ü/' => 'ue',
'/Ä/' => 'Ae',
'/Ü/' => 'Ue',
'/Ö/' => 'Oe',
'/À|Á|Â|Ã|Ä|Å|Ǻ|Ā|Ă|Ą|Ǎ|Α|Ά|Ả|Ạ|Ầ|Ẫ|Ẩ|Ậ|Ằ|Ắ|Ẵ|Ẳ|Ặ|А/' => 'A',
'/à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª|α|ά|ả|ạ|ầ|ấ|ẫ|ẩ|ậ|ằ|ắ|ẵ|ẳ|ặ|а/' => 'a',
);
/**
* Replaces all foreign characters listed in
* self::$foreign_characters with their given counterparts
* @param $string string to replace characters in
*/
public static function replace_chars_in($string)
{
foreach( self::$foreign_characters as $replace => $with )
{
$string = preg_replace($replace, $with, $string);
}
return $string;
}
}
I decided to create a class, because it provides an easy way to handle your replacements, and you can improve the functionality without any effort. I used a static function, so you do not need to instantiate it, the replacement would simply be done by calling Replacer::replace_chars_in();
. Try this:
echo Replacer::replace_chars_in("äÄfäüädasÖäǽasd");
it will output: aeAefaeueaedasOeaeaeasd
If you are unfamiliar with regular expressions, have a read of the PHP reference. There you can find a detailed explanation on how they work.
This post on character replacement and the strtr function might interest you as well.