I have this string:
= 1.0.2 - 2021-01-18 =
I am looking to use preg_match to extract the version number and the date from it and put it into an array, I have the following code but I’m definitely doing something wrong here:
preg_match('/^([d.]+)[- ](d{4}-dd-dd) =/', $string, $match)
I’m unsure how to deal with the = in the string and the hyphen in the middle or even if the above will successfully match a 3 digit version number and date.
I am expecting $match to contain an array of the version number and date.
How can I use preg_match to get this data in an array from the string?
Advertisement
Answer
If it’s not variable, just match what you want in the pattern. This assumes version could be 10.1.204
etc. and the date will always be YYYY-MM-DD
:
preg_match('/= (d+.d+.d+) - (d{4}-d{2}-d{2}) =/', $string, $match);
Or some minor corrections to yours:
/= ([d.]+)[s-]+(d{4}-dd-dd) =/
Or:
/^= ([d.]+)[s-]+(d{4}-dd-dd) =/
Then look in $match[1]
and $match[2]
. However, the trim
and explode
answer is probably better.