php的substr_replace将指定两位置之间的字符替换为*号的代码,需要的朋友可以参考下。
代码如下:
$username = "zongzi";
echo substr_replace($username,'**','1','2');
定义和用法substr_replace() 函数把字符串的一部分替换为另一个字符串。
语法substr_replace(string,replacement,start,length)
参数描述
string 必需。规定要检查的字符串。
replacement 必需。规定要插入的字符串。
start 必需。规定在字符串的何处开始替换。
正数 - 在第 start 个偏移量开始替换
负数 - 在从字符串结尾的第 start 个偏移量开始替换
0 - 在字符串中的第一个字符处开始替换
charlist 可选。规定要替换多少个字符。
正数 - 被替换的字符串长度
负数 - 从字符串末端开始的被替换字符数
0 - 插入而非替换
提示和注释注释:如果 start 是负数且 length 小于等于 start,则 length 为 0。
例子
代码如下:
<?php
echo substr_replace("hello world","earth",6);
?>
输出:
hello earth
以下方法能实现匹配关键词并分别对关键词做特殊处理的功能,代码如下
<?php
header("content-type: text/html; charset=utf-8");
function multiple_replace_words($word,$replace,$string,$tmp_match='#a_a#'){
preg_match_all('/'.$word.'/',$string,$matches); //匹配所有关键词
$search = explode(',','/'.implode('/,/',$matches[0]).'/');
//不存在匹配关键词
if(empty($matches[0])) return false;
//特殊替换设置
$count = count($matches[0]);
foreach($replace as $key=>$val){
if(!isset($matches[0][$key])) unset($replace[$key]); //剔除越界替换
}
//合并特殊替换数组与匹配数组
for($i=0;$i<$count;$i++){
$matches[0][$i] = isset($replace[$i])? $replace[$i] : $matches[0][$i];
}
$replace = $matches[0];
//防止替换循环,也就是替换字符仍是被替换字符,此时将其临时替换一个特定字符$tmp_match
$replace = implode(',',$replace);
$replace = str_replace($word,$tmp_match,$replace); //临时替换匹配字符
$replace = explode(',',$replace);
//替换处理
$string = preg_replace($search,$replace,$string,1); //每次只替换数组中的一个
$string = str_replace($tmp_match,$word,$string); //还原临时替换的匹配字符
return $string;
}
//示例1
$string = 'aaabaaacaaadaaa';
$word = 'aaa';
$replace = array(null,'xxx','yyy');
echo '原文:'.$string.'<br/>输出:'.multiple_replace_words($word,$replace,$string).'<br/><br/>';
//示例2
$string = '中文aaab中文ccaaad中文eee';
$word = '中文';
$replace = array(null,'(替换中文2)','(替换中文3)');
echo '原文:'.$string.'<br/>输出:'.multiple_replace_words($word,$replace,$string);
/*
输出结果:
原文:aaabaaacaaadaaa
输出:aaabxxxcyyydaaa
原文:中文aaab中文ccaaad中文eee
输出:中文aaab(替换中文2)ccaaad(替换中文3)eee
//*/
以上就是php数组一对一替换实现代码一句指定两位置之间的字符替换为*号的详细内容。