常用正则表达式~~

前端之家收集整理的这篇文章主要介绍了常用正则表达式~~前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

贪婪模式:

<?PHP
header('Content-type:text/html;charset=utf-8;');
var_dump(preg_match_all('/<div>(.+)<\/div>/','<div>aaa</div><div>bbb</div><div>ccc</div>',$a));
var_dump($a);
?>
输出(非贪婪模式)
array
  0 => 
    array
      0 => string '<div>aaa</div><div>bbb</div><div>ccc</div>' (length=42)
  1 => 
    array
      0 => string 'aaa</div><div>bbb</div><div>ccc' (length=31)
非贪婪模式
<?PHP
header('Content-type:text/html;charset=utf-8;');
var_dump(preg_match_all('/<div>(.+?)<\/div>/',$a));
var_dump($a);
?>
输出
array
  0 => 
    array
      0 => string '<div>aaa</div>' (length=14)
      1 => string '<div>bbb</div>' (length=14)
      2 => string '<div>ccc</div>' (length=14)
  1 => 
    array
      0 => string 'aaa' (length=3)
      1 => string 'bbb' (length=3)
      2 => string 'ccc' (length=3)


preg_replace_callback在类中的用法

<?PHP
header('Content-type:text/html;charset=utf-8;');
class ClassName
{
    public function str($str){
        $res=preg_replace_callback('/(\d){3}/',array($this,'replace'),$str);
        return $res;
    }
    function replace($maths){
        return $maths[0]=$maths[1];
    }
}
$obj=new ClassName();
$res=$obj->str(array('111sdfsdf222asdfsd444sdg','333sdf555dfgdfg55dfgdf999dfgdfg'));
var_dump($res);
?>

猜你在找的正则表达式相关文章