preg_match匹配src =,background =和url(..)

时间:2012-02-11 09:02:16

标签: php regex preg-match-all

我想找到一个正则表达式,可以找到(在给定的HTML中)以下图像:

  • src=""
  • 中捕获的内容
  • src=''
  • 中捕获的内容
  • background=""
  • 中捕获的内容
  • background=''
  • 中捕获的内容
  • url("")
  • 中捕获的内容
  • url('')
  • 中捕获的内容
  • url()
  • 中捕获的内容

到目前为止,我提出了:

preg_match_all("/src=((\"|'|)?(.*\.(png|gif|jpg))(\"|'|))/Ui", $strHTML, $arrMatches);

preg_match_all("/background=((\"|'|)?(.*\.(png|gif|jpg))(\"|'|))/Ui", $strHTML, $arrMatches);

preg_match_all("/url\((\"|'|)?((.*\.(png|gif|jpg))(\"|'|))\)/Ui", $strHTML, $arrMatches);

但那些不完整,因为它们不包含前缀(src / background / url)。此外,安全方面我认为可以进一步改进,以防止有人进入src="http://somesite.com/someurl.exe?ext=jpg"

对正确方向的任何帮助表示赞赏。

修改

我认为我得到了它,虽然代码肯定可以改进,甚至可能组合和/或优化:)

/* match CSS url() links */

preg_match_all("/(url\((\"|'|)(.*\.(png|gif|jpg|jpeg))(\"|'|)\))/Ui", $strHTML, $arrMatches);

Array
(
    [0] => Array
        (
            [0] => url('test1.gif')
            [1] => url(test2.gif)
            [2] => url("test3.gif")
        )

    [1] => Array
        (
            [0] => url('test1.gif')
            [1] => url(test2.gif)
            [2] => url("test3.gif")
        )

    [2] => Array
        (
            [0] => '
            [1] => 
            [2] => "
        )

    [3] => Array
        (
            [0] => test1.gif
            [1] => test2.gif
            [2] => test3.gif
        )

    [4] => Array
        (
            [0] => gif
            [1] => gif
            [2] => gif
        )

    [5] => Array
        (
            [0] => '
            [1] => 
            [2] => "
        )

)

/* match img links */
preg_match_all("/(src=(\"\'??)(.*\.(png|gif|jpg|jpeg))(\"\'??))/Ui", $strHTML, $arrMatches);

/* match background links */
preg_match_all("/(background=(\"\'??)(.*\.(png|gif|jpg|jpeg))(\"\'??))/Ui", $strHTML, $arrMatches);

1 个答案:

答案 0 :(得分:4)

如果你确定那些属性名称(src,url和background)......

$arr = array(
    'url("http://somesite.com/someurl.exe?src=jpg")',
    'url(http://somesite.com/someurl.exe?src=jpg)',
    'src="http://somesite.com/someurl.exe?src=jpg"',
    'src="http://somesite.com/someurl.exe?ext=jpg"',
    'background="http://somesite.com/someurl.exe?src=jpg"'
);
foreach ($arr as $str) {
    preg_match_all('/(?<=src=|background=|url\()(\'|")?(?<image>.*?)(?=\1|\))/i',$str,$matches);
    echo $str;
    foreach($matches['image'] as $img) {
        echo "\nimage: <b>$img</b>\n";
    }
    echo "\n";
}