Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

php - Removing blank lines from a textarea's output

I get data from a textarea where a user has to enter a name one on each line. That data later gets split at the carriage return. Sometimes a user may add blank lines intentionally. How can I detect these lines and delete them? I'm using PHP. I dont mind using a regexp or anything else.

Incorrect Data

Matthew
Mark
Luke

John

James

Correct Data (Note blank lines removed)

Matthew
Mark
Luke
John
James
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using regex to eliminate blank lines before exploding (works well for any number of consecutive blank lines, also see next snippet):

$text = preg_replace('/
+/', "
", trim($_POST['textarea']));

Splitting with a regex:

$lines = preg_split('/
+/', trim($_POST['textarea']));
$text = implode("
", $lines);

Splitting without a regex:

$lines = array_filter(explode("
", trim($_POST['textarea'])));
$text = implode("
", $lines);

Just feeling a tad creative today, pick your poison :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...