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?
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.
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);
精彩评论