本文共 884 字,大约阅读时间需要 2 分钟。
substr_replace 是一个用于替换字符串中指定子串的函数,广泛应用于文本处理和数据提取等场景。该函数的主要参数包括:
该函数不会修改原字符串,而是返回一个新字符串,操作后的结果可以通过变量赋值来获取。
示例:
$mobile = '18512341234';echo substr_replace($mobile, '****', 3, 4); // 输出:185****1234echo substr_replace($mobile, '****', -8, -4); // 输出:185****1234
Preg_replace 是一个强大的工具,用于在字符串中执行正则表达式搜索和替换操作。该函数的主要参数包括:
preg_replace默认是全局替换,即会将所有匹配的部分替换掉。要进行非全局替换,可以在替换内容前后添加\1、\2等引用符号。
示例:
$subject = 'Hello, World! This is a test string.';$pattern = '/\bHello\b/';$replacement = 'Hi, ';echo preg_replace($pattern, $replacement, $subject); // 输出:Hi, World! This is a test string.
此外,preg_replace支持使用捕获组,将匹配的部分保存起来,从而实现更灵活的替换操作。
转载地址:http://jmtfk.baihongyu.com/