質問

データファイル内で特定のブロックを見つけて、その中の何かを置き換えようとしています。その後、全体(データを置き換えたもの)を新しいファイルに入れます。現時点での私のコードは次のようになります。

$content = file_get_contents('file.ext', true);

//find certain pattern blocks first
preg_match_all('/regexp/su', $content, $matches);

foreach ($matches[0] as $match) {
  //replace data inside of those blocks
  preg_replace('/regexp2/su', 'replacement', $match);
}

file_put_contents('new_file.ext', return_whole_thing?);

さて、問題は、return_whole_thing を返す方法がわからないことです。基本的に、file.ext と new_file.ext は、データが置き換えられることを除けば、ほぼ同じです。代わりに何を置くべきかという提案はありますか return_whole_thing?

ありがとう!

役に立ちましたか?

解決

これは、元のパターン内のサブパターンを見つけるためにあなたの正規表現を強化するために、おそらく最善です。そのようにあなただけにpreg_replace()を呼び出すことができますし、それを使って行うこと。

$new_file_contents = preg_replace('/regular(Exp)/', 'replacement', $content);

これは、正規表現の中に「()」で行うことができます。 「正規表現のサブパターン」のための迅速なGoogle検索は、<のhref = "http://www.google.com/search?q=regular+expression+subpatterns&ie=utf-8&oe=utf-8&aq=t&rls=org.mozillaの結果:EN-US:公式&クライアント=のfirefox-」のrel = "nofollowをnoreferrer">このの

他のヒント

あなたもにpreg_replaceを必要としません。すでに試合を持っているので、あなたがちょうどそうのような通常のstr_replaceを使用することができます:

$content = file_get_contents('file.ext', true);

//find certain pattern blocks first
preg_match_all('/regexp/su', $content, $matches);

foreach ($matches[0] as $match) {
  //replace data inside of those blocks
  $content = str_replace( $match, 'replacement', $content)
}

file_put_contents('new_file.ext', $content);

あなたの問題を理解しているかわかりません。次のような例を投稿していただけますか。

  • file.ext、元のファイル
  • 使用する正規表現と一致するものを置き換える
  • new_file.ext、希望の出力

ただ読みたいだけなら file.ext, 、正規表現の一致を置き換え、結果を次の場所に保存します。 new_file.ext, 、必要なのは次のとおりです。

$content = file_get_contents('file.ext');
$content = preg_replace('/match/', 'replacement', $content);
file_put_contents('new_file.ext', $content);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top