Explode in PHP to separate characters


I need to make a split or explode in PHP of this string:

$nombre = I_20_IH_21_23_HP_junio.jpg; 

I have to do 3 strings separated by

  • I_ y _I ;
  • H_ y _H ;
  • P_ y .

I tried to do an explode but I do not know how to put a string that delimits it

$nombre = explode ( "I_",$file,"_I",0);

Thanks for the help!

asked by Csc99 25.04.2018 в 11:58

2 answers


In your case, I would use patterns with preg_match. I give you the example of the pattern of your case (from what I have understood, the values of what you want to get are between I_ and I, H and H and P y. Then your employer could be:


with preg_match you indicate the pattern, the string and the array where to save the results.

$nombre = "I_20_IH_21_23_HP_junio.jpg"; 
$patron = "/I_(.*)_IH_(.*)_HP_(.*)\./";
$result = preg_match($patron, $nombre, $resultados);


In the example, you could draw an array with four elements, the first is the whole chain, and the others are each of the substrings you are looking for.

In result you would have an array like the following:

    [0] => I_20_IH_21_23_HP_junio.
    [1] => 20
    [2] => 21_23
    [3] => junio

Your value of I is in index 1, H in index2 and P in index 3

answered by 25.04.2018 / 12:08

A trick to avoid the use of regular expressions when you do not master them, is to replace all the delimiters with the same delimiter in the chain to be exploited:

$nombre = 'I_20_IH_21_23_HP_junio.jpg'; 
$delimitadores=['I_','_I', 'H_', '_H', 'P_', '.'];

$nombre_modificado = str_replace($delimitadores,'|',$nombre);

echo $nombre_modificado;

He gives you:


And that you can now work by exploiting simply by | . But note that your original text will result in empty elements in the array, due to consecutive separators and the separator at the beginning of the string. That's your task left.

answered by 25.04.2018 в 13:29