[英]How to replace last 3 character with x from string in php?
$string = "Hello world country";
echo substr($string, 0, -3).'xxx';
实际 output:
Hello world counxxx
预期 output:
Hexxx woxxx counxxx
我怎样才能做到这一点?
你需要使用explode()
、 foreach()
、 implode()
和substr()
$string = "Hello world india";
$array = explode(' ',$string);
foreach($array as &$ar){
$ar = substr($ar, 0, -3).'xxx';
}
echo implode(' ',$array);
Output: https://3v4l.org/RhCA7
注意:我的假设是单词用空格分隔,每个单词的字母数 >= 3
@Alive to Die 提供的答案很棒。
另一种方法是使用str_word_count()
和array_map()
:
$string = "Hello world country";
$words = str_word_count($string, 1);
$words = array_map(function($word) {
if (strlen($word) < 3) return $word;
return substr($word, 0, -3) . 'xxx';
}, $words);
echo implode(' ', $words);
Output:
Hexxx woxxx counxxx
要掩盖每个单词的一半,您可以使用:
$string = "Hello world country";
$words = str_word_count($string, 1);
$words = array_map(function($word) {
$half = floor(strlen($word)/2);
return substr($word, 0, -$half) . str_repeat('x', $half);
}, $words);
echo implode(' ', $words);
output:
Helxx worxx counxxx
您可以使用explode
和substr
:
$string = "Hello world country";
$array = explode(' ',$string);
foreach($array as $ar){
$ar = substr($ar,0,-3).'xxx';
echo $ar." ";
}
预期 Output: Hexxx woxxx counxxx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.