Search code examples
phpexplode

Split string on multiple characters in PHP


I need to split an age into its components where the age is expressed as eg. 27y5m6w2d or any combination of those values. eg. 2w3d or 27d or 5y2d etc. Result has to be up to 4 variables $yrs, $mths, $wks and $days containing the appropriate numeric values.

I can do it with this code but am hoping there is something more efficient:

$pos = strpos($age, 'y');
if ($pos !== false)
   list($yrs, $age) = explode('y', $age);
$pos = strpos($age, 'm');
if ($pos !== false)
   list($mths, $age) = explode('m', $age);
$pos = strpos($age, 'w');
if ($pos !== false)
   list($wks, $age) = explode('w', $age);
$pos = strpos($age, 'd');
if ($pos !== false)
   list($days, $age) = explode('d', $age);

If you have a suggestion, please run it in a 10,000 iteration loop and advise the results. The code above runs in an average of 0.06 seconds for 10,000 iterations. I use this code to test:

<?php
$startTime = microtime(true);

// code goes here

echo "Time:  " . number_format(( microtime(true) - $startTime), 4) . " Seconds<br>"; 
echo 'y='.$yrs.' m='.$mths.' w='.$wks.' d='.$days;
?>

Solution

  • I'd go with the following approach.

    $age = '27y5m6w2d';
    
    // Split the string into array of numbers and words
    $arr = preg_split('/(?<=[ymdw])/', $age, -1, PREG_SPLIT_NO_EMPTY);
    
    foreach ($arr as $str) 
    {
        $item = substr($str, -1); // Get last character
        $value = intval($str);    // Get the integer
    
        switch ($item) 
        {
            case 'y':
                $year = $value;
                break;        
            case 'm':
                $month = $value;
                break;
            case 'd':
                $day = $value;
                break;
            case 'w':
                $week = $value;
                break;
        }
    }
    

    The code is more readable and slightly faster. I tested this with 10000 iterations and it took around just 0.0906 seconds.