【PHP】 ファイル内の文字を置換する方法

ファイルを読み込んでその中にある文字を置換する方法について記します。

使用例

//ファイルパス
$rdfile = './test.html';
$val = "目次";
 
//ファイルの内容を全て文字列に読み込む
$str = file_get_contents($rdfile);
 
//検索文字列に一致したすべての文字列を置換する
$str = str_replace("{mokuji}", $val, $str);
 
//文字列をファイルに書き込む
file_put_contents($rdfile, $str);

file_get_contents関数でtest.html内の文字を変数$strに入れます。

$str内にある文字列{mokuji}をstr_replace関数により”目次”に置換します。

file_put_contents関数で編集した内容をtest.html内に戻します。

使用関数

file_get_contents
http://php.net/manual/ja/function.file-get-contents.php

str_replace
http://php.net/manual/ja/function.str-replace.php

file_put_contents
http://php.net/manual/ja/function.file-put-contents.php

簡単な置換であれば数行でできるので便利ですね。

Share this content: