0

I am trying to execute a preg_match to get the complete match of the pattern, and I don't need the sub-matches.

Here is the code that I am using:

$text = 'abc.php?v=2&g=js';
// Pattern to check
$pattern_array = array('abc\.php\?v=\d+&(amp;)?g=js', 'xyz\.php');
$pattern = '/(' . implode('|', $pattern_array) . ')/i';
echo 'Pattern:' . $pattern . '<br />';
preg_match($pattern, $text, $matches);
if (!empty($matches)) 
{
    echo 'pattern found';
}
else
{
    echo 'pattern not found';
}
var_dump($matches);

I am getting the following output:

Pattern: /(abc\.php\?v=\d+&(amp;)?g=js|xyz\.php)/i
pattern found
array (size=3)
  0 => string 'abc.php?v=2&amp;g=js' (length=20)
  1 => string 'abc.php?v=2&amp;g=js' (length=20)
  2 => string 'amp;' (length=4)

However, I just want the output to be just the following from the matches array.

  0 => string 'abc.php?v=2&amp;g=js' (length=20)

Also, in case my $text matches multiple patterns, I want to be able to see all those patterns.

4

1 回答 1

0

只需将组设为非捕获,(?:...)而不是(...)

$pattern_array = array('abc\.php\?v=\d+&(?:amp;)?g=js', 'xyz\.php');
//                                    ___^^
$pattern = '/(?:' . implode('|', $pattern_array) . ')/i';
//         ___^^
于 2013-10-12T09:44:12.740 回答