我想用"*"
替换字符串的特定区域。我尝试PHP substr_replace
但它对我不起作用。
我有一个这样的名字:
Jhon Smith
我只想显示姓名和姓氏的起始字母。我想用"*"
更改其他字母。
所以输出应该是这样的:
J*** S****
我怎样才能用PHP做到这一点?
您可以使用正则表达式并preg_replace_callback()
:
<?php
$name = 'John Smith';
$name = preg_replace_callback('/'w+/u', function($match) {
return $match[0][0] . str_repeat('*', strlen($match[0]) - 1);
}, $name);
var_dump($name);
// string(10) "J*** S****"
演示
它是如何工作的?
'w+
匹配一个"单词"(a-z, A-Z, 0-9),匿名方法返回单词的第一个字母(match[0][0]
),后跟字符*
重复单词的长度(match[0]
)减去一。
/u
修饰符物种 unicode。因此,我们还匹配名称,例如 Günther
.
这意味着match[0][0]
将是例如。"约翰"中的"J"和"史密斯"中的"S",长度减去一将是"约翰"的"3"和"史密斯"的4。
有几种方法可以做到这一点。我已经给你写了一个小的帮助程序函数,它将完成你需要的东西。
function cleanName($string = 'Jhon Smith')
{
// Get all the pieces of the name
$pieces = explode(' ', $string);
// Loop through each piece and replace asterisks where necessary
foreach($pieces as $key => $value)
{
// Get the length of the string
$length = strlen($value);
// Calculate how many asterisks are needed
$asterisks = $length - 1;
// Show / start with the first letter of the string
$name = substr($value, 0, 1);
// Add the asterisks to the end of the string
for($i = 1; $i <= $asterisks; $i++)
{
$name .= '*';
}
// Create the name 'part'
$parts[] = $name;
}
// Recreate the name
$name = implode(' ', $parts);
echo $name;
}
您可以通过调用函数并在每次出现时替换字符串来使用它:
cleanName('Jane Smith');
还有其他方法可以实现此目的,例如使用正则表达式。考虑到你对这个主题听起来有点陌生,我假设你不知道正则表达式,尤其是preg_replace,所以我偏离了它。
对于拍摄和咯咯笑声,我根据@h2ooooooo的答案做了一个函数,试图找到最有效的方法来操纵字符串。
function cleanName($string)
{
return implode(' ',
array_map(function($substr){
return mb_strtoupper(substr($substr,0,1)).str_repeat('*',(strlen($substr) - 1));
},
explode(' ', $string)
)
);
}
php小提琴