Separate and extract elements of a string with numbers and letters!

2

How can I extract certain elements from a chain? example:

 $cadena="11d08mo2016y";

from which I need to extract only the given numbers of x string separately, thus remaining!

$cadena[0]=11
$cadena[1]=08
$cadena[2]=2016

I was trying the explode function, but apparently it does not destroy the chain in parts, thank you in advance!

 $day= explode("d",$cadena);
    
asked by matteo 15.11.2017 в 15:27
source

3 answers

2

explode separates by the delimiter that you give it, in this case "d" , so it will bring 2 chains the result [11, 08mo2016y] to the second result you would have to do another explode with the second element and so on, you can do it by recursion or iteration

function explodeFecha($dato) {
   $delimitadores = ['d', 'mo', 'y'];
   $arreglo = [];
   foreach($delimitadores as $delimiter) {
      $explodeDato = explode($delimiter, $dato);
      $arreglo[] = $explodeDato[0];
      $dato = isset($explodeDato[1])? $explodeDato[1] : NULL;
      //si usas php 7 o sueperior puedes usar para simplificar
      //$dato = $explodeDato[1] ?? NULL;
   }
   return $arreglo;
}

print_r(explodeFecha('11d08mo2016y'));

It would also be advisable to validate that the format is the desired one so that errors do not appear

    
answered by 15.11.2017 / 15:48
source
4

The first thing is to eliminate the letters while converting the string at the same time into a array , that you do it by means of the following function:

$cadena="11d08mo2016y";
$array = preg_split('/[^0-9]+/i', $cadena);

Then to make sure there are no blank spaces we filter to array forming a new one without those spaces:

$array_sin_espacios = array_filter($array, function($dato){
    if($dato == ''){
        return false;
    }else{
        return true;
    }
});

var_dump($array_sin_espacios);
    
answered by 15.11.2017 в 16:06
2

You can use the function preg_split and apply a regular expression, something like this:

$cadena="11d08mo2016y";
$r = preg_split("/[A-Za-z]+/", $cadena);
print_r($r);
    
answered by 15.11.2017 в 15:56