preg_replace与preg_replace_callback

// preg_replace
// 删除空格
$str = 'runo o   b';
$str = preg_replace('/\s+/', '', $str);
// 将会改变为'runoob'
echo $str;

// preg_replace_callback
// 将文本中的年份增加一年.
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
// 回调函数
function next_year($matches)
{
  // 通常: $matches[0]是完成的匹配
  // $matches[1]是第一个捕获子组的匹配
  // 以此类推
  // print_r($matches);
  return $matches[1].($matches[2]+1);// 替换完成匹配,也就是$matches[0]
}
echo preg_replace_callback(
            "|(\d{2}/\d{2}/)(\d{4})|",
            "next_year",
            $text);


// 下划线转驼峰
echo ucfirst(preg_replace_callback(
            "/_([A-Za-z])/",
            function ($match)
            {
            	return strtoupper($match[1]);
            },
            $a)),"\n";

// 驼峰转下划线
$c = 'AaaaBbbbCccc';
echo strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $c));

猜你喜欢

转载自blog.csdn.net/weixin_38230961/article/details/106210985