如何在每第n个宽度处插入一个字符作为字符串?
例如
$input = 'テスaトテaストa’;
// Insert 'x' every 5th width
$output = 'テスaxトテaxストax’;
答案 0 :(得分:0)
您需要这个:
<?php
$input = "テスaトテaストa";
$tempStr = '';
$count = 0;
for ($i = 0; $i < strlen($input); $i++) {
$currChar = $input[$i];
$countTemp = mb_strwidth($currChar);
$count = $count + $countTemp;
if($count == 7){
$tempStr = $tempStr.$currChar.'x';
$count = 0;
}
else{
$tempStr = $tempStr.$currChar;
}
}
echo $tempStr; // will print テスaxトテaxストax
另一种解决方案
<?php
function split($str, $len = 1) {
$arr = array();
$length = mb_strlen($str, 'UTF-8');
for ($i = 0; $i < $length; $i += $len) {
$arr[] = mb_substr($str, $i, $len, 'UTF-8');
}
return $arr;
}
$input = "テスaトテaストa";
$parts = split($input, 3);
$final = implode("x", $parts).'x';
echo $final; // will print テスaxトテaxストax
答案 1 :(得分:-2)
@haris莎玛怎么说,它的解决方案在How do I insert a string after every 50 words using php
中可用$parts = str_split($input, 5);
$final = implode("x", $parts);