I have spent a few hours on this and cannot figure it out but due to my lack of preg_match knowledge even after studying it may be something easy. This works 开发者_如何学JAVAin removing multiple lines into one line:
$string = preg_replace('/^\n|^[\t\s]\n/m', "", $string);
How can I reverse its function so that it ignores multiple lines and removes single lines of space? So if the input is:
one
two
three
It would remove the space between one and two, but ignore the multiple spaces before three so the result would look like:
one
two
three
Thanks.
EDIT POST
Thanks guys. 3emad, your code works for my example. I was wrong, I want this to work with code instead of just my text and when I tried using
// ----- limits -----
$new_limit = 7; // maximum days in What's New section
$hot_limit = 20; // top 20 most accessed links
$toprated_limit = 20; // top 20 most rated links
// ----- bold the keyword in search result -----
$bold_keyword = 1;
it didn't remove the single line between the variables while ignoring the double space leading to the comments.
Here is the regular expression:
[\r|\r\n](?=\w)
This works for your example, you can test it at: RegExr
the secret was to use a positive look ahead matching, you can learn more about "look ahead" here
$str = '// ----- limits -----
$new_limit = 7; // maximum days in What\'s New section
$hot_limit = 20; // top 20 most accessed links
$toprated_limit = 20; // top 20 most rated links
// ----- bold the keyword in search result -----
$bold_keyword = 1;';
echo '<pre>';
echo preg_replace('/\r?\n(?=[\w|\$])/m','',$str);
echo '</pre>';
Helpful PHP reference for regular expressions
Not sure this is perfect solution for you, this will remove extra line + extra space + tabs
<?php
$input="this is nimit
and friends
this must be in single line.
@234 234234
I have test this.
";
$input = str_replace(' ','_',$input);
$result = preg_replace('/\s+/','<br>',$input);
$result = str_replace('_',' ',$result);
echo $result;
?>
精彩评论