1. 程式人生 > >php使用正則表示式提取字串中尖括號、小括號、中括號、大括號中的字串

php使用正則表示式提取字串中尖括號、小括號、中括號、大括號中的字串

</pre><p>PHP使用正則表示式提取字串中尖括號<>、小括號()、中括號[]、大括號{}中的字元示例,需要的朋友可以參考下</p><p></p><p><pre name="code" class="php">$str="你好<我>(愛)[北京]{天安門}"; 
echo f1($str); //返回你好 
echo f2($str); //返回我 
echo f3($str); //返回愛 
echo f4($str); //返回北京 
echo f5($str); //返回天安門 
function f1($str) 
{ 
$result = array(); 
preg_match_all("/^(.*)(?:<)/i",$str, $result); 
return $result[1][0]; 
} 

function f2($str) 
{ 
$result = array(); 
preg_match_all("/(?:<)(.*)(?:>)/i",$str, $result); 
return $result[1][0]; 
} 
function f3($str) 
{ 
$result = array(); 
preg_match_all("/(?:\()(.*)(?:\))/i",$str, $result); 
return $result[1][0]; 
} 
function f4($str) 
{ 
$result = array(); 
preg_match_all("/(?:\[)(.*)(?:\])/i",$str, $result); 
return $result[1][0]; 
} 
function f5($str) 
{ 
$result = array(); 
preg_match_all("/(?:\{)(.*)(?:\})/i",$str, $result); 
return $result[1][0]; 
}