preg_match
preg_math($reg,$str)
在$str中尋找正則reg,存在返回1,否則返回0;preg_math_all($reg,$str,$arr)
在$str中尋找匹配正則reg的個數,將所有匹配正則$reg的內容逐個存入$arr數組
//聲明一個字符串
$str = "bagldghsghdk";
//在字符串中搜索正則表達式"/a/",存在返回1,否則返回0;
preg_match("/a/",$str);
//在字符串中搜索正則表達式"/b/",返回"/b/"的數目;
preg_match_all("/b/",$str,$arr);
preg_replace
preg_replace($reg,"改變的內容",$str)
在$str尋找所有匹配正則$reg的內容,將之改變爲第二個參數中的內容,
//聲明字符串
$str = "[email protected],[email protected]";
//聲明正則
$reg = "/@\d+/"
//改變字符串中匹配正則的內容
$str = preg_replace($reg,"y123",$str);
//輸出
echo "$str"
preg_split
preg_split($reg,$str)
將字符串$str匹配正則$reg的部分劈開構成數組
$str = "abc123dsdf456";
$reg = '/[a-z]+/';
$arr = preg_split($reg, $str);
print_r($arr);
preg_grep
preg_grep($reg,$arr)
在數組$arr中的每個值匹配正則$reg,能匹配的保留,不能匹配的刪除,返回一個新數組
$arr = [12,'ab12c',53,'c1',10,'e',2];
$reg = '/\d\d/';
$newarr = preg_grep($reg,$arr);
print_r($newarr);
正則獲取網頁內容
//獲取網頁"http://www.sina.com.cn"中的內容
$con = file_get_contents("http://www.sina.com.cn");
//匹配h3標籤
$reg = '/<h3>.+<\/h3>/';
//選出h3標籤內的內容
preg_match_all($reg,$con,$arr);
//輸出
print_r($arr);