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

Categories

0 votes
544 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
See Question&Answers more detail:os

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

1 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...