PHP str_replace()関数
例
文字列「Helloworld!」の文字「world」を置き換えます。「ピーター」と:
<?php
echo str_replace("world","Peter","Hello world!");
?>
定義と使用法
str_replace()関数は、文字列内の一部の文字を他の一部の文字に置き換えます。
この関数は、次のルールに従って機能します。
- 検索する文字列が配列の場合、配列を返します
- 検索する文字列が配列の場合、すべての配列要素に対して検索と置換が実行されます
- findとreplaceの両方が配列であり、replaceの要素がfindより少ない場合、空の文字列がreplaceとして使用されます
- findが配列で、replaceが文字列の場合、replace文字列がすべての検索値に使用されます
注:この関数では大文字と小文字が区別されます。str_ireplace()関数を使用して、大文字と小文字を区別しない検索を実行します。
注:この関数はバイナリセーフです。
構文
str_replace(find,replace,string,count)
パラメータ値
Parameter | Description |
---|---|
find | Required. Specifies the value to find |
replace | Required. Specifies the value to replace the value in find |
string | Required. Specifies the string to be searched |
count | Optional. A variable that counts the number of replacements |
技術的な詳細
戻り値: | 値が置き換えられた文字列または配列を返します |
---|---|
PHPバージョン: | 4歳以上 |
変更ログ: | countパラメーターはPHP5.0で追加されました。PHP4.3.3 より前では、この関数で配列を検索パラメーターと置換パラメーターの両方として使用すると問題が発生し、置換配列の内部ポインターを進めずに空の検索インデックスがスキップされていました。新しいバージョンでは、この問題は発生しません。PHP 4.0.5以降、ほとんどのパラメーターを配列にすることができます |
その他の例
例
配列とカウント変数でstr_replace()を使用する:
<?php
$arr = array("blue","red","green","yellow");
print_r(str_replace("red","pink",$arr,$i));
echo "Replacements: $i";
?>
例
findよりもreplaceの要素が少ないstr_replace()を使用する:
<?php
$find = array("Hello","world");
$replace = array("B");
$arr = array("Hello","world","!");
print_r(str_replace($find,$replace,$arr));
?>
❮PHP文字列リファレンス