nciaer 发表于 2024-4-12 16:12:04

正则替换例子

1. 替换***的内容
$str = '我是hellohello,你呢?';
$pattern = '/\(.*?)\[\/img\]/';
$newMessage = preg_replace($pattern, '', $str); // 结果:我是,你呢?


2. 如果我只是想删除,保留hello该怎么办呢?,这个,上面这个(.*?)可以用$1或者\1来引用。也就是可以这么写:$str = '我是https://www.nciaer.com/hellohello,你呢?';
$pattern = '/\(.*?)\[\/img\]/';
$newMessage = preg_replace($pattern, '$1', $str); // 结果:我是hello,你呢?
第一个小括号的引用用$1,第二个用$2,以此类推

3.如果想保留hello,还可以用preg_replace_callback函数,给个例子:
$str = '我是https://www.nciaer.com/hellohello,你呢?';
$pattern = '/\(.*?)\[\/img\]/';
$newMessage = preg_replace_callback($pattern, 'foo', $str);
function foo($matches) {
    return $matches;
}
符合正则的会调用foo函数,$matches就是匹配到的内容,foo函数的返回值会替换匹配的内容,这个例子就会把https://www.nciaer.com/hellohello替换成hello









页: [1]
查看完整版本: 正则替换例子