Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Character substitution 1

Status
Not open for further replies.

Extension

Programmer
Joined
Nov 3, 2004
Messages
311
Location
CA

Hi,

I'm looking for a simple way to achieve character substitutions. I need to convert french accents to normal characters. Example: é to e.

So I was wondering if there's a cleaner way to do it.

Code:
$string = "résumÉ ôter lake";

for ($string) {
	s/-/ /g;
	s/ //g;	
	s/á/a/g;
	s/Á/A/g;	
	s/à/a/g;
	s/À/A/g;	
	s/â/a/g;
	s/Â/A/g;	
	s/é/e/g;
	s/É/E/g;
	s/è/e/g;
	s/È/E/g;
	s/ê/e/g;
	s/Ê/E/g;
	s/ç/c/g;
	s/Ç/C/g;
	s/ô/o/g;
	s/Ô/O/g;
	tr/a-z/A-Z/;
}

print "Should be: RESUMEOTERLAKE \n";
print "$string \n";

Thank you in advance
 
Yep, "tr".
Code:
tr[from][to];
[code]
Replace "from" with all the characters that you wish to translate and the "to" with a list of what you want to change them to.  This allows you to do them all in one go.


Trojan.
 
Thank Trojan for your help.

It's alot cleaner using tr

Code:
$string =~ tr[à,á,â,ä,å,æ,ã][a,a,a,a,a,a,a];

But what about replacing the dashes and whitespaces by a blank (nothing). How shoud I handle this. Just with a regexp before the translation ?

Thanks
 
There should be no comma between the characters in a tr/// transliteration. This will be enough:
Code:
$string =~ tr[àáâäåæã][aaaaaaa];

It's a tricky one to spot because it has the effect of replacing commas with commas as well as the other substitutions, thus having no noticeable effect.
 
I also find the use of square brackets in the tr/// operator to be a bit confusing, I would stick with:

tr/searchlist/replacelist/

when you only want to use one replacement character you can use a shortcut list:

$string =~ tr/àáâäåæã/a/;

perl automatically repeats the replacement character as much as needed.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top