Muhammed Talha Akbar
Muhammed Talha Akbar

Reputation: 313

PHP: preg_match_all consider two equal matches as one

I want to extract some of the data from a string (HTML, actually). I searched a bit and found preg_match_all. The issue is that if there are two equal matches, the function considers them as two and make space for both. My code, code's output and code's expected output will clearly explain.

<?php
    $html = "
        <!doctype html>
        <html lang=\"en\">
        <head>
            <meta charset=\"UTF-8\">
            <title>Document</title>
        </head>
        <body>
            <img src=\"[profileLink@user:0]\" />
            <img src=\"[profileLink@user:0]\" />
        </body>
        </html>
    ";
    $regex = "/\[(.*?)@(.*?)\]/";
    preg_match_all($regex, $html, $matches);
    var_dump($matches);
?>

Output:

array (size=3)
  0 => 
    array (size=2)
      0 => string '[profileLink@user:0]' (length=20) // It looks ok
      1 => string '[profileLink@user:0]' (length=20) // Don't want it.
  1 => 
    array (size=2)
      0 => string 'profileLink' (length=11) // It looks ok
      1 => string 'profileLink' (length=11) // Don't want it.
  2 => 
    array (size=2)
      0 => string 'user:0' (length=6) // It looks ok
      1 => string 'user:0' (length=6) // Don't want it.

Expected output:

array (size=3)
  0 => 
    array (size=1)
      0 => string '[profileLink@user:0]' (length=20)
  1 => 
    array (size=1)
      0 => string 'profileLink' (length=11)
  2 => 
    array (size=1)
      0 => string 'user:0' (length=6)

Upvotes: 0

Views: 47

Answers (1)

StathisG
StathisG

Reputation: 1169

Using preg_match instead of preg_match_all, the outcome will be:

array(3) {
  [0]=>
  string(20) "[profileLink@user:0]"
  [1]=>
  string(11) "profileLink"
  [2]=>
  string(6) "user:0"
}

Upvotes: 1

Related Questions