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.

Iszak

03-11-2009, 09:31 AM

You could use something like this - I would of filled in the other conversions, but.. I don't know how it works.

<?php
$string = 'fromlatter="asdfghjkl.."';

preg_match('#(?:from|to)latter="([^"]+)"#i', $string, $match);

$search = array(
'a',
's',
'd',
'f'
);

$replace = array(
'o',
'l',
'i',
'f'
);

echo str_ireplace($search, $replace, $match[1]);

This will only work if the content between the two "" does not contact " as soon as it does, it'll stop at that point. e.g.

tolatter="asd"fghjkl.."

will only convert "asd", I hope this helps.

kamkam

03-11-2009, 10:52 AM

Thanks, the str_ireplace() works very good for me, but i want to ask compare with strtr, which one more safety, and faster.

Which seems to be what you want to do. The only complication is that rather than having two arrays, one containing the letters to be replaced, and the other containing the letters to replace them with, you seem to have two strings. So if you can take those two strings, $from_letter and $to_letter, and convert them to arrays, your problem would be solved. The shortest way to do that is this:

This is just one way to turn a string into an array of letters. preg_split splits up strings using a regular expression. The regular expression I passed, '//', is actually a blank regular expression, and so it automatically splits the string up after every single letter. This also gives two extra values, because you end up with a blank entry at the start and end of the array. The array_splice just strips out these blank entries. Then, str_replace is ran on the original string, with the arrays created from preg_split. Make sense?

cmancone

03-11-2009, 06:35 PM

Obviously there are plenty of ways to turn a string into an array. You could also do this: