PHP - 强制在preg_match_all中忽略相同的值

时间:2014-11-28 15:28:31

标签: php preg-match-all

我遇到了preg_match_all函数的问题,默认情况下会自动忽略相同的值。

代码:

$data = '<img src="images/smiles/lol.gif" alt="Laughing" border="0">  <img src="images/smiles/lol.gif" alt="Laughing" border="0">  <img src="images/smiles/lol.gif" alt="Laughing" border="0">';
preg_match_all('#<img src="images/smiles/(.+?)" alt=".+" border="0">#',$data,$out);
print_r($out);

结果:

Array
(
    [0] => Array
        (
            [0] => <img src="images/smiles/lol.gif" alt="Laughing" border="0">  <img src="images/smiles/lol.gif" alt="Laughing" border="0">  <img src="images/smiles/lol.gif" alt="Laughing" border="0">
        )

    [1] => Array
        (
            [0] => lol.gif
        )

)

我希望$out变量是这样的:

Array
(
    [0] => Array
        (
            [0] => <img src="images/smiles/lol.gif" alt="Laughing" border="0">
            [1] => <img src="images/smiles/lol.gif" alt="Laughing" border="0">
            [2] => <img src="images/smiles/lol.gif" alt="Laughing" border="0">
        )

    [1] => Array
        (
            [0] => lol.gif
            [1] => lol.gif
            [2] => lol.gif
        )

)

我应该添加或更改哪个标志或参数以具有上述输出? 提前谢谢!

修改

当然,我不会在$data变量中只包含这些HTML标记,还有其他一些和文本。

1 个答案:

答案 0 :(得分:2)

试试这个:

$data = '<img src="images/smiles/lol.gif" alt="Laughing" border="0">  <img src="images/smiles/lol.gif" alt="Laughing" border="0">  <img src="images/smiles/lol.gif" alt="Laughing" border="0">';
preg_match_all('#<img[^>]+src\\s*=\\s*[\'"]images/smiles/([^\'"]+)[\'"][^>]*>#i', $data, $out);
var_dump($out);

输出是:

array
  0 => 
    array
      0 => string '<img src="images/smiles/lol.gif" alt="Laughing" border="0">' (length=59)
      1 => string '<img src="images/smiles/lol.gif" alt="Laughing" border="0">' (length=59)
      2 => string '<img src="images/smiles/lol.gif" alt="Laughing" border="0">' (length=59)
  1 => 
    array
      0 => string 'lol.gif' (length=7)
      1 => string 'lol.gif' (length=7)
      2 => string 'lol.gif' (length=7)