Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace foreign characters

Tags:

php

I need to be able to replace some common foreign characters with English equivalents before I store values into my db.

For example: æ replace with ae and ñ with n.

Do I use preg_replace?

Thanks

like image 775
santa Avatar asked Dec 08 '10 15:12

santa


People also ask

How do I replace a character with another character?

To replace or substitute all occurrences of one character with another character, you can use the substitute function. The SUBSTITUTE function is full automatic. All you need to do is supply "old text" and "new text". SUBSTITUTE will replace every instance of the old text with the new text.

How do you replace special characters in regex?

To replace special characters, use replace() in JavaScript.


2 Answers

You can define your convertable characters in an array, and use str_replace():

$conversions = array(
    "æ" => "ae",
    "ñ" => "n",
);

$text = str_replace(array_keys($conversions), $conversions, $text);
like image 65
István Ujj-Mészáros Avatar answered Sep 24 '22 03:09

István Ujj-Mészáros


For single character of accents

$str = strtr($str, 
  "ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÝßàáâãäåçèéêëìíîïñòóôõöøùúûüýÿ",
  "AAAAAACEEEEIIIINOOOOOOYSaaaaaaceeeeiiiinoooooouuuuyy"); 

For double character of accents (such as Æ, æ)

$match   = array('æ', 'Æ');
$replace = array('ae', 'AE');
$str = str_replace($replace, $replace, $str);
like image 24
ajreal Avatar answered Sep 22 '22 03:09

ajreal