coderex
coderex

Reputation: 27875

Why does my preg_replace() on multi-line file contents on Windows fail?

I have a text file Qfile.txt and the contents are follows, and want to create another file with the same informations and but answers are diffrent. Qfile1.txt,Qfile2.txt

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"

I want to read the questions from the Qfile.txt and store the informations to Qfile1.txt with in PHP. I wrote some code but the pattern matching is not working:

$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);
}

The preg_replace($pattern, $replacement, $contents); is not working.

Upvotes: 1

Views: 658

Answers (1)

chaos
chaos

Reputation: 124325

Unable to replicate; your code, suitably adapted, actually works fine for me. The only thing I can think of is that perhaps you're writing this on a Windows machine and your text file has CRLF line terminators. In that case, you'd need to change your code to:

$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);
}

The changes are on the $pattern = and $replacement = lines. I've written it so that it will preserve whichever line termination pattern is in place (out of the two it supports, LF and CRLF).

Upvotes: 3

Related Questions