I have a string similar to tvm11551.iso that I am trying to parse. In this string, these bolded numbers vary: tvm 11 5 51 .iso (please ignore the spaces here). I wrote the following program in PHP that would extract those two numbers from that string:
$a = "tvm11551.iso";
if(preg_match('/^tvm\d{5}\.iso/',$a)){
$b = preg_match('/tvm(\d\d)\d\d\d\.iso/' , $a);
$c = preg_match('/tvm\d\d\d(\d\d)\.iso/' , $a);
echo "B: " . $b . "<br>";
echo "C: " . $c;
}
However, I am getting the output as:
B: 1
C: 1
How do I fix the RegEx to get the expected output?
The 1 you are seeing as output is the number of matches, not their contents, that preg_match() returns on a successful match. Since each of your tests had only one () capture group, one match was returned. You need to capture matches into an array as the third argument to preg_match():
$a = "tvm11551.iso";
$matches = array();
preg_match('/^tvm(\d{2})5(\d{2})\.iso$/', $a, $matches);
var_dump($matches);
array(3) {
[0] =>
string(12) "tvm11551.iso"
[1] =>
string(2) "11"
[2] =>
string(2) "51"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With