PHP中preg_match_all函數正則匹配詳解

來源:互聯網
上載者:User

preg_match_all — 執行一個全域Regex匹配

int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )

 代碼如下 複製代碼

<?php
preg_match_all("|<[^>]+>(.*)</[^>]+>|U",
    "<b>example: </b><div align=left>this is a test</div>",
    $out, PREG_PATTERN_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "n";
echo $out[1][0] . ", " . $out[1][1] . "n";
?>

如何擷取偽靜態url中的參數變數,已經對應的值。

比如說。你現在url的是這樣的。/js/d1b3cid419299191rs好指令碼

你的.htaccess檔案會這樣寫rewirte規則 RewriteRule ^js/(.*)$ /index.php?m=Sell&a=index&g=$1 [QSA,PT,L]

這樣你就可以把g接收過來。

 代碼如下 複製代碼

$get = 'd1b3cid419299191rs好指令碼';
$rs_pos = strpos($get,'rs');
if($rs_pos !== false)
{
    $rs = substr($get,$rs_pos);
    $rs = str_replace('rs','',$rs);
    $rs = strpos($rs,'/')!==false ? substr($rs,0,strpos($rs,'/')) : $rs;
    $get = substr($get,0,$rs_pos);
}
echo 'keywords='.$rs;
echo '<br>';
preg_match_all('/([a-z]*)([0-9]+)/',$get,$m);
if($m)
{
        $k = $v = '';
        $count = count($m[1]);
        for($i = 0; $i <= $count; $i++)
        {
            ${$m[1][$i]} = $m[2][$i];
            if(isset(${$m[1][$i]}))
            {   
                echo $m[1][$i].'='.${$m[1][$i]};
                echo '<br>';
            }
        }
}

結果:keywords=好指令碼,d=1,b=3,cid=419299191

 

匹配文章中的圖片

 

 代碼如下 複製代碼

<?php
$con = file_get_contents("http://www.111cn.net/");
$pattern="/<[img|IMG].*?src=['|"](.*?(?:[.gif|.jpg|.png]))['|"].*?[/]?>/";
preg_match_all($pattern,$con,$match);
print_r($match);
?>

輸出代碼

Array
(
[0] => Array
(
[0] => <img src="yun_qi_img/logo.png" alt="" />
[1] => <img style="display: block; margin-left: auto; margin-right: auto;" title="" src="yun_qi_img/531656480.jpg" alt="2" />
[2] => <img style="display: block; margin-left: auto; margin-right: auto;" src="yun_qi_img/2647136297.jpg" alt="875EA1C00E50B4542797E24FA6E7E1F2.jpg" />
)
[1] => Array
(
[0] => yun_qi_img/logo.png
[1] => yun_qi_img/531656480.jpg
[2] => yun_qi_img/2647136297.jpg
)
)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.