Rahul Desai
Rahul Desai

Reputation: 15501

need regex to extract two substrings from one string

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?

Upvotes: 2

Views: 679

Answers (3)

Michael Berkowski
Michael Berkowski

Reputation: 270617

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"
}

Upvotes: 5

Oussama Jilal
Oussama Jilal

Reputation: 7739

preg_match returns the number of times the pattern matched (but since preg_match always stops at the first match it finds, it always returns 0 or 1). if you want to get the numbers that got matched, you haves to pass an array as the third parameter for preg_match. see preg_match documentation

Upvotes: 1

KRyan
KRyan

Reputation: 7598

Based on the patterns you have, I don't see any reason to be using RegEx at all, after the initial match.

You would just want this:

if(preg_match('/^tvm\d{5}\.iso/',$a)){
    $b = substr($a, 3, 5);
    $c = substr($a, 6, 8);

Upvotes: 3

Related Questions