tags:

views:

111

answers:

1

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.

+3  A: 

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).

chaos
yes am working on windows machine.
coderex
That's your problem, then. Modify your code per above and that should fix it.
chaos
yes its working tanQz a lot :)
coderex
is the same code works in Linux machine?
coderex
Yup, should be fine on either platform.
chaos
$1 ?? what is that??
coderex
You see in the `$pattern` where I made it do `(\r?\n)`? That means "accept either `\r\n` or `\n`, and put whichever it is into `$1`". That's how I made it compatible with both Windows and Linux; it stores whichever line termination pattern it found and re-uses it when it puts in your data.
chaos
Ok i understood it really very helpful, once again thank you mr chaos
coderex
You're welcome. FYI, I'm translating "what `(\r?\n)` means" *very* loosely; when you have the chance, you should look into more about grouping / parenthesis capturing in PHP regular expressions. This looks like a likely place: http://www.webcheatsheet.com/php/regular_expressions.php
chaos