0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PHP str_replace()関数:文字列を別の文字列に置き換える

0
Posted at

概念と使用方法

PHPバージョン 4+
str_replace()関数は、文字列の中から特定の文字列を検索して別の文字列に置き換える関数です。
str_replace()関数は、指定された文字列の中から指定した文字列を検索して、置換文字列に置き換える役割を果たします。

基本例

$str = 'Hello, world!';
$new_str = str_replace('world!', 'universe!', $str);
echo $new_str;

// 出力 : Hello, universe!

構文

str_replace(
    array|string $search,
    array|string $replace,
    string|array $subject,
    int &$count = null
): string|array

// str_replace(検索する文字列, 置換する文字列, 対象の文字列[, カウント]);

戻り値

str_replace()関数は、置換処理が行われた後に対象の文字列または文字列の配列を返します。
関数は置換処理の後、対象の文字列または文字列の配列を返します。

使い方

# 特定の文字を別の文字に置き換える場合

$original_string = 'Hello, world! Hello, PHP!';
$new_string = str_replace('Hello', 'Hi', $original_string);

echo $new_string;  // 出力: 'Hi, world! Hi, PHP!'

# 特定の文字列を削除する場合

$str = 'This is a test';
$new_str = str_replace('test', '', $str);
echo $new_str; // 出力: 'This is a'

# str_replace()関数で配列を使い、複数の文字列を置き換える例

$original_array = ['Apples are red.', 'Bananas are yellow.', 'Apples and bananas are delicious.'];

$search = ['Apples', 'Bananas'];
$replace = ['Oranges', 'Grapes'];

$new_array = str_replace($search, $replace, $original_array);

print_r($new_array);

/* 出力:
Array
(
    [0] => Oranges are red.
    [1] => Grapes are yellow.
    [2] => Oranges and grapes are delicious.
)
*/

参考資料

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?