0

私はテキストを持っているとしましょう:

この行は、%title% というテキストの最初の行です

この行は 2 番目の行です

3 行目の %title% は置き換えないでください

...

最後の行

今私はPHPを使いたいので、テキストは次のようになります:

この行は、MY_TITLE と呼ばれるこのテキストの最初の行です

この行は 2 番目の行です

3 行目の %title% は置き換えないでください

...

最後の行

3 行目の %title% にも注意してください

それを行うための最良の(最速の)方法は何ですか?

4

3 に答える 3

4

最初の行のみを変数にロードしてから、str_ireplace最初の行とファイルの残りの部分を一緒に戻すことができます。

$data = explode("\n", $string);
$data[0] = str_ireplace("%title%", "TITLE", $data[0]);    
$string = implode("\n", $data);

これは最も効率的な方法ではありませんが、コーディングに適していて高速です。

于 2013-06-04T13:18:49.887 に答える
3

preg_replace()を使用できます。これは 1 行のコードです ;)

$str = "this line is the first line of this text called %title%\n
this line is the second one\n
the third line, %title% shouldn't be replaced\n
last line";

echo preg_replace('/%title%$/m','MY_TITLE',$str);

正規表現の説明:

  • /%title%意味%title%
  • $行の終わりを意味します
  • m入力の開始 (^) と入力の終了 ($) コードを作成し、それぞれ行頭と行末をキャッチします

出力:

this line is the first line of this text called MY_TITLE
this line is the second one the third line, %title% shouldn't be replaced
last line
于 2013-06-04T13:25:15.997 に答える