$string = "Hello world country";
echo substr($string, 0, -3).'xxx';
Actual output:
Hello world counxxx
Expected output:
Hexxx woxxx counxxx
How can I do this?
You need to use explode()
, foreach()
, implode()
and 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
Note: My assumption here is words are separated with space and each word have letter count >= 3
Answer provided by @Alive to Die is great.
Another way is to use str_word_count()
and 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
To mask the half of each words, you could use:
$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
You can use explode
and substr
:
$string = "Hello world country";
$array = explode(' ',$string);
foreach($array as $ar){
$ar = substr($ar,0,-3).'xxx';
echo $ar." ";
}
Expected Output: Hexxx woxxx counxxx
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.