Reputation: 53
i have a mysql database that store up 1m ads. This ads have field "Ad_Content" and have random examples (Ad_Content):
1 CASE: \r\n{text...text...text...}\r\n\r\n\r\n <- This row is good
2 CASE: {text...text...}\r\n \r\n\r\n <- Wrong, have 1 space beetwen string "\r\n\r\n"
3 CASE: \r\n \r\n{text...}\r\n\r\n\r\n \r\n <- Wrong, have 2 spaces beetwen string "\r\n\r\n"
4 CASE: \r\n \r\n\r\n\r\n{text...text...}\r\n \r\n\r\n \r\n <- Wrong, have 3 spaces beetwen string "\r\n*"
I try to remove all spaces found in the string "\r\n group" with REGEX but i can't get its.
Expected examples:
1 CASE: \r\n{text...text...}\r\n\r\n <- This row is good
2 CASE: {text...text...}\r\n\r\n\r\n (good)
3 CASE: \r\n\r\n{text...}\r\n\r\n\r\n\r\n (good)
4 CASE: \r\n\r\n\r\n\r\n{text...text...}\r\n\r\n\r\n\r\n (good)
My code is:
$adContent = $getDataAd->Ad_Content;
// This REGEX its ok, replace all \r\n\r\n\r\n\r\n... for 2 <br> but broken if detect a space :(
$pattern = "/(?:\r?\n[ ]*)+/";
$adContent = preg_replace($pattern, "<br><br>", $adContent);
Thanks :)
Upvotes: 1
Views: 34
Reputation: 522301
You may do a regex replacement on the following pattern:
\r\n\s+(?=\r\n)
Sample script, using your third example as input:
$input = "\r\n \r\n\r\n\r\n{text...text...}\r\n \r\n\r\n \r\n";
$output = preg_replace("/\r\n\s+(?=\r\n)/", "\r\n", $input);
The trick here is to use the lookahead (?=\r\n)
to assert, but not consume, a required following CRLF. This way, we allow for the possibility of that following CRLF to also have unwanted spaces in front of it.
Upvotes: 1