tags:

views:

36

answers:

2

I have a form with a textarea in it. I log the results to a text file on the server, but I would like to strip out any line breaks a user would put in the textarea, as well as any commas that would interfere with importing the comma-delimited log text file into Excel or something for later use.

I think this has to do with regex, but I'm no expert and could use some help. Or maybe there is an easy PHP function that will do it?

A: 

Using str_replace to replace a couple of characters by a space should work ; for example :

$str = "This is a \nnewline, and, some, commas\nagain";
$new_str = str_replace(array("\n", "\r", ","), " ", $str);
var_dump($new_str);

Will get you :

string 'This is a  newline  and  some  commas again' (length=43)


You could probably also use strtr for that :

$new_str = strtr($str, "\n\r,", "   ");


But note that, if escaping the data properly in your CSV file (using fputcsv, maybe ?), it should be able to contain newlines and commas without any problem -- at least if the software used to read it is respecting the standard too.

Pascal MARTIN
Hrm, I will have to look into fputcsv, I was just using basic fwrite. Thanks!
bccarlso
You're welcome :-) Have fun !
Pascal MARTIN
@Pascal MARTIN Hrm, have been playing around with it, but no luck getting it to work. File set up with correct permissions and everything… do you know of any good tutorials online?
bccarlso
+1  A: 

If you're only going to be doing a couple of characters, you can use str_replace

$cleaned_textarea_data = str_replace(
    array(",", "\n"), 
    array("", " "), 
    $textarea_data
);

Otherwise, if it gets more complicated, you can use preg_replace

$cleaned_textarea_data = pregr_replace("`[,\n]`", "", $textarea_data);
Justin Johnson