views:

1628

answers:

2

I have a form that allows the user to either upload a text file or copy/paste the contents of the file into a textarea. I can easily differentiate between the two and put whichever one they entered into a string variable, but where do I go from there?

I need to iterate over each line of the string (preferably not worrying about newlines on different machines), make sure that it has exactly one token (no spaces, tabs, commas, etc.), sanitize the data, then generate an SQL query based off of all of the lines.

I'm a fairly good programmer, so I know the general idea about how to do it, but it's been so long since I worked with PHP that I feel I am searching for the wrong things and thus coming up with useless information. The key problem I'm having is that I want to read the contents of the string line-by-line. If it were a file, it would be easy.

I'm mostly looking for useful PHP functions, not an algorithm for how to do it. Any suggestions?

+3  A: 

preg_split the variable containing the text, and iterate over the returned array

foreach(preg_split("/(\r?\n)/", $subject) as $line){
    // do stuff with $line
}
Kyril
Will this handle ^M in addition to \n\r ?
Topher Fangio
I'm not sure if the ascii carriage return gets converted to \r once it's placed inside a variable. If not you can always use a split()/exlope() with the ascii value instead -- ch(13)
Kyril
A: 

Kyril's answer is best considering you need to be able to handle newlines on different machines.

"I'm mostly looking for useful PHP functions, not an algorithm for how to do it. Any suggestions?"

I use these a lot:

explode() can be used to split a string into an array, given a single delimiter.

implode() is explode's counterpart, to go from array back to string.

jfkiley