2009-07-24 6 views
1

私はテキストファイルQfile.txtを持っていて、その内容は次のとおりで、同じ情報を持つ別のファイルを作成したいのですが、答えは異なります。 Qfile1.txt、Qfile2.txtWindows上の複数行のファイルコンテンツにある私のpreg_replace()が失敗するのはなぜですか?

Qfile.txt

Question "What is your age?" 
Answer "" 

Question "What you doing?" 
Answer "" 

Question "What is you name?" 
Answer "" 

Qfile1.txt

Question "What is your age?" 
Answer "25" 

Question "What you doing?" 
Answer "chatting" 

Question "What is you name?" 
Answer "Midhun" 

私はQfile.txtからの質問を読みたいです情報をQfile1.txt に保存してください。私はいくつかのコードを書いたが、パターンマッチングが機能していません。

$contents=file_get_contents("Qfile.txt"); 
foreach(/*bla bla*/) 
{ 
    $pattern = "/Question \"".preg_quote($id, '/')."\"\nAnswer \"\"/"; 

    $string = str_replace('"', '\"', $string); 

    $replacement = "Question \"$id\"\nAnswer \"". $string . "\""; 

    $result = preg_replace($pattern, $replacement, $contents); 
} 

preg_replace($pattern, $replacement, $contents);が機能していません。

答えて

3

複製できません。あなたのコードは、適切に適応され、実際にはうまく動作します。私が考えることができるのは、おそらくあなたはWindowsマシン上でこれを書いており、あなたのテキストファイルにはCRLF行ターミネータがあるということだけです。その場合、あなたはあなたにコードを変更する必要があるだろう:

$contents=file_get_contents("Qfile.txt"); 
foreach(/*bla bla*/) 
{ 
    $pattern = "/Question \"".preg_quote($id, '/')."\"(\r?\n)Answer \"\"/"; 

    $string = str_replace('"', '\"', $string); 

    $replacement = "Question \"$id\"$1Answer \"". $string . "\""; 

    $result = preg_replace($pattern, $replacement, $contents); 
} 

変更が$pattern =$replacement =ライン上にあります。私はそれが書かれているので、それがサポートしている2つのLFとCRLFのうち、どこに行終了パターンが保存されていても保持します。

+0

はいWindowsマシンで作業しています。 – coderex

+0

それはあなたの問題です。上記のコードを修正してください。 – chaos

+0

はいその多くの作業tanQz :) – coderex

関連する問題