Reputation: 3496
My Input file like this
Header1,,,,,,,,,,,
c1 , c2 , c3 ,,,,
22-02-2017,1-2,10,,,,
22-02-2017,2-3,11,,,,
22-02-2017,4-6,10,,,,
22-02-2017,5-8,11,,,,
I need to regex to achive below expected output:
Header1,,,,,,,,,,,
c1 , c2 , c3 ,,,,
22-02-2017,1-2,10,,,,
22-02-2017,2-3,11,,,,
22-02-2017,4-6,10,,,,
22-02-2017,5-8,11,,,,
I trying this regex for search \s\n in REplaceTExt and replacement value is \n.
After Replace text output content like below.,
Header1,,,,,,,,,,,c1 , c2 , c3 ,,,,22-02-2017,1-2,10,,,,22-02-2017,2-3,11,,,,22-02-2017,4-6,10,,,,
But my regex worked perfectly in regexr website.
Is there is any other regex to search empty rows and combine rows before and after of empty rows?
Upvotes: 1
Views: 987
Reputation: 48001
Sahil's solution is not as refined as it could be:
You can match with this pattern: \n+\s
and replace with \n
. Demo
This will provide the same result with fewer steps.
The points to keep in mind with this very simple task is that using "alternatives" (pipes |
) adds steps to your pattern and should be avoided when possible.
When alternatives are necessary, order the alternatives from shortest to longest -- this will provide greater efficiency.
Lastly, do not repeat characters in your pattern, use quantifiers -- this again improves performance. When comparing \n\n\s|\n\s
versus \n{2}\s|\n\s
, the latter will outperform the former simply by using the {2}
quantifier.
Probably the best advice would be to read your file with file()
(which delivers an array of lines) and set the desired flags.
$array = file('yourfile.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
This prevents needing to perform the extra preparation step with regex or a replacing string function.
fgetcsv()
is a great companion for this approach.
Upvotes: 1