Note that there are some explanatory texts on larger screens.

plurals
  1. POFix for PHP parsing plain text?
    text
    copied!<p>I have a php script which I am using to parse some plain text to a CSV format.</p> <pre><code>&lt;?php $text = "1. Bonus: Name some things about US history. For 10 points each: [10] Name the first president of the United States of America. ANSWER: George Washington [10] How many original colonies were there? ANSWER: 13 [10] How many states exist today? ANSWER: 50"; function text_to_csv( $text = null ) { $lines = explode( "\n", $text ); $data = array(); $temp = array(); foreach( $lines as $line ) { $line = trim( $line ); if ( empty( $line ) ) { continue; } if ( preg_match( '/^\[10\](.+?)$/', $line, $quest ) ) { $temp[] = trim( $quest[0] ); continue; } if ( preg_match( '/^([0-9]+)\.(.+?)$/', $line, $quest ) ) { $temp[] = trim( $quest[1] ); $temp[] = trim( $quest[2] ); continue; } if ( preg_match( '/^ANSWER\:(.+?)$/', $line, $quest ) ) { $temp[] = trim( $quest[1] ); $data[] = "|".implode( '|,|', $temp )."|"; $temp = array(); } } return implode( "\r\n", $data ); } echo text_to_csv( $text ); ?&gt; </code></pre> <p>This returns:</p> <pre><code>|1|,|Bonus: Name some things about US history. For 10 points each:|,|[10] Name the first president of the United States of America.|,|George Washington| |[10] How many original colonies were there?|,|13| |[10] How many states exist today?|,|50| </code></pre> <p>The second and third [10] are on separate lines and do not coincide with the first. What I would like the output to be is:</p> <pre><code>|1|,|Bonus: Name some things about US history. For 10 points each:|,|[10] Name the first president of the United States of America.|,|George Washington|,|[10] How many original colonies were there?|,|13|,|[10] How many states exist today?|,|50| </code></pre> <p>The entire string is all on one line and separated by commas. I think what is happening is the script is treating the second and third [10] as new entries rather than connected to the previous array. Can anybody help me fix this. It would be greatly appreciated!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload