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 Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

replace some corresponding letters from a string 1

Status
Not open for further replies.

xbl12

Programmer
Dec 12, 2006
66
Hi;

I got a string(myString)which will be replaced some letter. and also i got another two of string, one is fromlatter="asdfghjkl.."
, and another one is tolatter="olik90=ky...", the two strings of the fromlatter and to latter are same length, the length may be more than
200.

And i want to if myString has a letter a will change to o, s=>l, d=>i, f=>k .. and so on.


Could anyone tell me how to do that, please.
 
Do you know exactly which letters will be changed, or does it depend on the situation? The changes you show here seem a bit random...

The basic concept of replacing is:

Code:
str_replace("a","o",mystring);

You could create an array of the letters to change from and to and then loop through it... but that's probably not the best way.
 
in fact you do not need to loop through arrays. you can do this instead

Code:
$search = array('a', 'e', 'i', 'o', 'u');
$replace = array('z', 'y', 'x', 'w', 'v');
$text = ($search, $replace, $mystring);

but be careful with this as the replacements are done sequentially and so if the z were replaced with an 'e', you would find that all 'a' and 'e' become 'y'. If this is a potential issue then strtr() is a better bet.
 
Does the final line not require a command to initiate the three items to interact?

I did not realise you could replace arrays of items, very useful.
 
Oh, it's just clicked what you're asking, you want the two strings to convert from the first string to the second string, like some kind of code cipher creater?

I have no idea how that could be done, but I misunderstood you so I feel I need to get it back on track so someone else can help you!
 
>Do you know exactly which letters will be changed, or does >it depend on the situation?

yes, i do. it is same as following;
$search = array('a', 'e', 'i', 'o', 'u');
$replace = array('z', 'y', 'x', 'w', 'v');


Thanks for your help.
 
Hi jpadie;

The both are works, but you prefer strtr than the another one, it is more safe , is it right?
 
sorry. the last line of my code should have had a function prepended. In this case str_replace.

@xbl12: in most cases I think that strtr() is 'safer'. However there may well be times when you want the behaviour of str_replace. it's horses for courses.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top