PHPで文字列を挿入する
PHPの場合、文字列の挿入は簡単に行うことができます。
今回はその方法を4つのパターンに分けて解説します。
1バイト文字のみの場合
1バイト文字のみの場合はsubstr_replaceを使うことで文字の挿入ができます。
PHPマニュアル:substr_replace
1バイト文字のみの場合
function insertStr1($text, $insert, $num){
return substr_replace($text, $insert, $num, 0);
}
//ab|Text|cdef
echo insertStr1('abcdef', '|Text|', 2);
2バイト文字を含む場合
2バイト文字を含んでいる場合は、substr_replaceを使うことができません。
そのため、preg_replaceを使います。
また、パターン修飾子とメタ文字を使うことによって位置を決定し、そこを置換することで挿入として機能させています。
PHPマニュアル:preg_replace
PHPマニュアル:パターン修飾子
PHPマニュアル:メタ文字
2バイト文字を含む場合
function insertStr2($text, $insert, $num){
return preg_replace("/^.{0,$num}+\K/us", $insert, $text);
}
//あいう|文字|えお
echo insertStr2('あいうえお', '|文字|', 3);
指定した文字数毎に挿入(1バイト文字のみ)
指定した文字数毎に文字列を挿入したい場合は、wordwrapを使います。
PHPマニュアル:wordwrap
指定した文字数毎に挿入(1バイト文字のみ)
function insertStr3($text, $insert, $num) {
return wordwrap($text, $num, $insert, true);
}
//ABC|text|DEF|text|GHI|text|JKL|text|MN
echo insertStr3('ABCDEFGHIJKLMN', '|text|', 3);
指定した文字数毎に挿入(2バイト文字を含む)
preg_replaceを工夫して用いることで、2バイト文字を含む文字列に対して指定した文字数毎に文字列を挿入することができます。
指定した文字数毎に挿入(2バイト文字を含む)
function insertStr4($text, $insert, $num){
$returnText = $text;
$text_len = mb_strlen($text, "utf-8");
$insert_len = mb_strlen($insert, "utf-8");
for($i=0; ($i+1)*$num<$text_len; $i++) {
$current_num = $num+$i*($insert_len+$num);
$returnText = preg_replace("/^.{0,$current_num}+\K/us", $insert, $returnText);
}
return $returnText;
}
//あいう|文字|えおか|文字|きくけ|文字|こ
echo insertStr4('あいうえおかきくけこ', '|文字|', 3);