PHP substr_replace()関数
例
「Hello」を「world」に置き換えます。
<?php
echo substr_replace("Hello","world",0);
?>
定義と使用法
substr_replace()関数は、文字列の一部を別の文字列に置き換えます。
注:開始パラメーターが負の数で、長さが開始以下の場合、長さは0になります。
注:この関数はバイナリセーフです。
構文
substr_replace(string,replacement,start,length)
パラメータ値
Parameter | Description |
---|---|
string | Required. Specifies the string to check |
replacement | Required. Specifies the string to insert |
start | Required. Specifies where to start replacing in the string
|
length | Optional. Specifies how many characters should be replaced. Default is the same length as the string.
|
技術的な詳細
戻り値: | 置き換えられた文字列を返します。文字列が配列の場合、配列が返されます |
---|---|
PHPバージョン: | 4歳以上 |
変更ログ: | PHP 4.3.3以降、すべてのパラメーターが配列を受け入れるようになりました |
その他の例
例
文字列の6番目の位置から置換を開始します(「world」を「earth」に置き換えます)。
<?php
echo substr_replace("Hello world","earth",6);
?>
例
文字列の末尾から5番目の位置から置換を開始します(「world」を「earth」に置き換えます)。
<?php
echo substr_replace("Hello world","earth",-5);
?>
例
「world」の先頭に「Hello」を挿入します。
<?php
echo substr_replace("world","Hello ",0,0);
?>
例
一度に複数の文字列を置き換えます。各文字列の「AAA」を「BBB」に置き換えます。
<?php
$replace = array("1: AAA","2: AAA","3: AAA");
echo implode("<br>",substr_replace($replace,'BBB',3,3));
?>
❮PHP文字列リファレンス