I need to separately extract the components of a file name with the following structure: FullName WorkerNumber HomeWork.pdf (For example: Pepe Solaz Gorro 123456 01092016.pdf
)
These files do NOT always include the third start date parameter or the second worker number parameter. On the other hand, the name can contain spaces or hyphens for example, so that a simple "explode" was not going to solve my life either.
This is the code I have so far, and it extracts both the worker name and worker number fine, but I am unable to get the date out.
//ejemplo de variable inicial
$path = "path1/path2/Pepe Solaz Gorro 123456 01092016.pdf"
//separamos por /
$partes = explode("/", $path);
$var1 = $partes[0];
$var2 = $partes[1];
$fichero = utf8_encode($partes[2]);
//extraemos el numero de trabajador
preg_match('/[0-9]+/', $fichero, $ntrab);
As far as I have been able to understand, preg_match, if we put the third parameter ( $ntrab
in this case) it should collect in an array all the matches it finds with the condition, in this case any number between 0 and 9, so I understand that $ntrab[0]
it should contain 123456 01092016, $ntrab[1]
123456 and $ntrab[2]
01092016 but I'm sure I misunderstood it, because I can't get the 01092016 out of the initial string.
Test:
You will have the results in the $results variable, which will be an array that will look like this:
And if we have no doubt about the length in digits of the numeric fields (with the date there shouldn't be) we can fix the position by specifying it:
Using the function
preg_match_all
you can get both numeric strings with the approximation you have used in your example, it gives a multidimensional array with all the matches.