PHP-php 替换字符串中间位置字符为星号

需求定制 需求定制 主题:1050 回复:2283

PHP-php 替换字符串中间位置字符为星号

偏爱自由 发布于 2017-04-21 字数 108 浏览 1017 回复 4

例如:

test        -> t**t 
tests -> te**s
exceptions -> exc*****ns

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

支持 Markdown 语法,需要帮助?

评论(4

甜柠檬 2017-10-24 4 楼

这个能满足你的要求:

function half_replace($str){
    $len = strlen($str)/2;
    return substr_replace($str,str_repeat('*',$len),ceil(($len)/2),$len);
}

echo half_replace('test'),"n",half_replace('tests'),"n",half_replace('exceptions');

想挽留 2017-09-30 3 楼

 function half_replace($str){
$c = strlen($str)/2;
return preg_replace('|(?<=.{'.(ceil($c/2)).'})(.{'.floor($c).'}).?|',str_pad('',floor($c),''),$str,1);
}

调用:

 echo half_replace('tes'),"<br/>n",half_replace('test'),"<br/>n",half_replace('tests'),"<br/>n",half_replace('exceptions');

虐人心 2017-07-25 2 楼

//方法1
function str_mid_replace($string) {
if (! $string || !isset($string[1])) return $string;

$len = strlen($string);
$starNum = floor($len / 2); 
$noStarNum = $len - $starNum;
$leftNum = ceil($noStarNum / 2); 
$rightNum = $noStarNum - $leftNum;

$result = substr($string, 0, $leftNum);
$result .= str_repeat('*', $starNum);
$result .= substr($string, $len-$rightNum);

return $result; 

}
//方法2
function str_mid_replace2($string) {
if (! $string || !isset($string[1])) return $string;

$len = strlen($string);
$starNum = floor($len / 2); 
$noStarNum = $len - $starNum;
$leftNum = ceil($noStarNum / 2); 
$starPos = $leftNum;
for($i=0; $i&lt;$starNum; $i++) $string[$starPos+$i] = '*';

return $string;

}

echo 'test=>'.str_mid_replace('test').PHP_EOL;

echo 'tests=>'.str_mid_replace('tests').PHP_EOL;

echo 'exceptions=>'.str_mid_replace('exceptions').PHP_EOL;

echo 'test=>'.str_mid_replace2('test').PHP_EOL;
echo 'tests=>'.str_mid_replace2('tests').PHP_EOL;
echo 'exceptions=>'.str_mid_replace2('exceptions').PHP_EOL;

想挽留 2017-06-11 1 楼

 <?php
$str = "ag";
function replace_star($str)
{
switch(strlen($str))
{
case 1: return $str . "";
case 2: return substr($str, 0, 1) . "
" . substr($str, 1, 1);
default:
return preg_replace("/(?<=.).+?(?=.)/", "*", $str);
}
}

echo replace_star("a") . "n";
echo replace_star("ab") . "n";
echo replace_star("abc") . "n";
echo replace_star("abcdef") . "n";