Instead of using RegEx, you can immediately add one additional check, for example:
if (ctype_alpha($testcase)) { // Return the value it only letters } else if(ctype_digit($testcase)) { // Return the value it only numbers } else { //RegEx your string to split nums and alphas }
EDIT: Obviously, my answer did not provide evidence that would work better, so I did a test that produced the following result:
- preg_split took 5.3319189548492 seconds
- sscanf took 3.4432129859924 seconds
And the answer was to be sscanf
Here is the code that gave the result:
$string = "AAAAAAAAAA111111111111111"; $count = 1000000; function prSplit($string) { return preg_split( '/([A-Za-z]+)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); } function sScanfTest($string) { return sscanf($string, "%[AZ]%[0-9]"); } function microtime_float() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } $startTime1 = microtime_float(); for($i=0; $i<$count; ++$i) { prSplit($string); } $time1 = microtime_float() - $startTime1; echo '1. preg_split took '.$time1.' seconds<br />'; $startTime2 = microtime_float(); for($i=0; $i<$count; ++$i) { sScanfTest($string); } $time2 = microtime_float() - $startTime2; echo '2. sscanf took '.$time2.' seconds';
Alex Rashkov
source share