Languages :: PHP :: turning letters into numbers |
|||
| By: roe1and |
Date: 05/11/2007 17:32:37 |
Points: 20 | Status: Answered Quality : Excellent |
|
$input = "001215adc"; $from_this = array("a", "b", "c", "d", "e"); $to_this = array("1", "2", "3", "4", "5"); $new = str_replace($from_this, $to_this, $input); echo $new; this outputs: 001215143, which is great. is there an easier way to do this? |
|||
| By: VGR | Date: 05/11/2007 18:44:19 | Type : Answer |
|
| grand classique : untested code but you'll get the idea // basis : $str='001215adc'; $ll=strlen($str); for ($i=0;$i<$ll;$i++) if (!is_numeric(c=str)) echo ord(c)-48; else echo c; |
|||
| By: VGR | Date: 05/11/2007 18:45:09 | Type : Comment |
|
| it should read "c=$str [ $i ]" | |||
| By: VGR | Date: 05/11/2007 18:45:30 | Type : Comment |
|
| $c of course. | |||
| By: VGR | Date: 05/11/2007 20:15:22 | Type : Comment |
|
| the first one is faster (no surprise) by a factor eight to ten (8 to 10) <?php // // testnumericrepl.php // //require_once('timer.inc.php'); $input = "001215adc054zedrft4578tyhgreds89hjpodiwnvtsrz64457125001215adc054zedrft4578tyhgreds89hjpodiwnvtsrz64457125001215adc054zedrft4578tyhgreds89hjpodiwnvtsrz64457125001215adc054zedrft4578tyhgreds89hjpodiwnvtsrz64457125001215adc054zedrft4578tyhgreds89hjpodiwnvtsrz64457125001215adc054zedrft4578tyhgreds89hjpodiwnvtsrz64457125"; echo "replacing non-numeric characters in '$input' with their alphabetic rank... "; echo '<hr>method 1 : str_replace(arrays) '; TimerStart(); $from_this = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'); $to_this = array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26'); $new = str_replace($from_this, $to_this, $input); echo $new; TimerStop(TRUE); // display elapsed time echo '<hr>method 2 : for loop+Ord() '; TimerStart(); $input=strtoupper($input); $ll=strlen($input); $new=''; for ($i=0;$i<$ll;$i++) if (!is_numeric($c=$input[$i])) $new.=ord($c)-64; else $new.=$c; echo $new; TimerStop(TRUE); ?> can be seen in action in here |
|||
| By: roe1and | Date: 06/11/2007 15:25:05 | Type : Comment |
|
| i tried your example above with a 1mb file and the time for str_replace showed as 5.95 seconds and the ord + loop came up as 9.5. i'll be using the str_replace is will help me get rid of double spaces in my data too " " -> " ". thanks for your help again. |
|||
|
Do register to be able to answer |
|||
| Add This Article To: | |||
| |
|
|
|
| |
|
|
|








