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
350 views
in Technique[技术] by (71.8m points)

regex - How do I remove blank lines from text in PHP?

I need to remove blank lines (with whitespace or absolutely blank) in PHP. I use this regular expression, but it does not work:

$str = ereg_replace('^[ ]*$
?
', '', $str);
$str = preg_replace('^[ ]*$
?
', '', $str);

I want a result of:

blahblah

blahblah

   adsa 


sad asdasd

will:

blahblah
blahblah
   adsa 
sad asdasd
question from:https://stackoverflow.com/questions/709669/how-do-i-remove-blank-lines-from-text-in-php

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

1 Reply

0 votes
by (71.8m points)
// New line is required to split non-blank lines
preg_replace("/(^[
]*|[
]+)[s]*[
]+/", "
", $string);

The above regular expression says:

/(^[
]*|[
]+)[s]*[
]+/
    1st Capturing group (^[
]*|[
]+)
        1st Alternative: ^[
]*
        ^ assert position at start of the string
            [
]* match a single character present in the list below
                Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
                
 matches a carriage return (ASCII 13)
                
 matches a fine-feed (newline) character (ASCII 10)
        2nd Alternative: [
]+
            [
]+ match a single character present in the list below
            Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
            
 matches a carriage return (ASCII 13)
            
 matches a fine-feed (newline) character (ASCII 10)
    [s]* match a single character present in the list below
        Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
        s match any white space character [
f ]
        Tab (ASCII 9)
    [
]+ match a single character present in the list below
        Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
        
 matches a carriage return (ASCII 13)
        
 matches a fine-feed (newline) character (ASCII 10)

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

...