3

I am not sure how to name what I need, I want in PHP to convert characters into a more "normal" character set, like for example:

ş to become s
ţ to become t, 
ă to become a

I am having Romanian town names and I want to use more "normal" characters in the URL. I guess I want to convert Romanian characters to US (or whatever is the right name to call this).

adrianTNT
  • 3,671
  • 5
  • 29
  • 35

6 Answers6

6

What you want to do is called transliteration. There is a Transliterator in the intl extension (PHP 5.4 only): http://www.php.net/manual/en/transliterator.transliterate.php

Example:

$str = 'àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ';
$rule = 'NFD; [:Nonspacing Mark:] Remove; NFC';

$myTrans = Transliterator::create($rule); 
echo $myTrans->transliterate($str);

//aaaaaceeeeiiiinooooouuuuyy
//AAAAACEEEEIIIINOOOOOUUUUY
Florian Klein
  • 8,692
  • 1
  • 32
  • 42
  • That probably would work nicely but my plesk panels don't seem to have PHP 5.4 yet and class is missing. Maybe on next updates. – adrianTNT Sep 21 '13 at 09:49
5

How about this:

$text = str_replace(array("ş","ţ","ă"),array("s","t","a"),$text);
seanbreeden
  • 6,104
  • 5
  • 36
  • 45
  • Thank you, this method worked nicely. I thought there is some kind of converting function in order to do this tough. Something like `normalize_chars("şţă");` – adrianTNT Feb 12 '12 at 22:05
2

I would go on a more complex transliteration system which PHP gives us. Is about iconv function.

An example would be like the following:

$city = iconv('UTF-8', 'ASCII//TRANSLIT', $city);
var_dump($city);
2

You could use str_replace.

$text = str_replace( array( 'ş', 'ţ', 'ă' ), array( 's', 't,', 'a' ), $text );
Will
  • 19,661
  • 7
  • 47
  • 48
2

As was already told here what you want to do is called transliteration, but this may not always work correctly in your case - what you really want to do is generate a 'slug' (don't ask me why it's called like that...) from human provided input to use i.e. in urls.

Take a look at this code : http://trac.symfony-project.org/browser/plugins/sfPropelActAsSluggableBehaviorPlugin/lib/sfPropelActAsSluggableBehaviorUtils.class.php to see how to make reliable url-safe and human-readable identifiers.

Mariusz Sakowski
  • 3,232
  • 14
  • 21
0

Have a look into strtr which replaces specific characters with specific replacements.

echo strtr($string, "äåö", "aao");
Joe
  • 15,669
  • 4
  • 48
  • 83
  • This seems to be meant for what I wanted BUT it returned some strange characters, I did it with `str_replace` to avoid trying to debug the `strtr` method. Thanks. – adrianTNT Feb 12 '12 at 22:06