48
35

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【PHP】複数文字列の置換(str_replace)

Last updated at Posted at 2015-04-19

str_replace()で複数文字列の置換ができる。

sourceをSourceに、destinationをDestinationに置換したい場合、以下のように一括で置換できる。

$subject= "source:XXX destination:XXX";
$search = array('source','destination');
$replace = array('Source','Destination');

echo str_replace($search,$replace,$subject);
//=>Source:XXX Destination:XXX

置換が配列の順番で対応しているので、対象の数が増えた場合に変換前と変換後の対応付けがわかりづらくなる。
その場合、連想配列で対応づけを行い、array_keys()とarray_values()でわけるとわかりやすい。

$subject= "source:XXX destination:XXX";

$table = array(
  'source'=>'Source',
  'destination'=>'Destination'
);

$search = array_keys( $table);
$replace = array_values( $table);

echo str_replace($search,$replace,$subject);
//=>Source:XXX Destination:XXX

参考:複数文字列置換を簡単に書く

48
35
1

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
48
35

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?