php - preg_replace replace line breaks across multiple lines between two symbols
Solution:
You can use
{-code-1}
See the regex demo{-code-7} Details:
{-code-2}
- end of the previous successful match ({-code-3}
) or ({-code-4}
) start of string ({-code-5}
) and then{-code-6}
or{-code-7}
[{-code-5}{]*?
- any zero or more (but as few as possible) chars other than{
\K
- match reset operator that discards all text matched so far in the overall match memory buffer\s+
- any one or more whitespace chars{-code-7}
Note the m
flag that is necessary to make {-code-5}
match start of a line, not just start of a whole string{-code-7}
See the PHP demo:
$text = "{-code-7}a {\r\n // rules\r\n}\r\n\r\n{-code-7}a-b,\r\n{-code-7}a-b {-code-7}b, {-code-7}a-b{-code-7}s\r\n{-code-7}x {-code-7}y, {-code-7}x {\r\n // rules\r\n}\r\n\r\n{-code-6}a {\r\n // rules\r\n}\r\n\r\n{-code-6}k {\r\n // rules\r\n}";
echo {-code-1};
Answer
Solution{-code-10}
Update{-code-10} Stupildy, I missed that this was a PHP question, not a JS one{{-code-9}code{-code-9}5} My answer is JS{-code-9}based; however it is easily adapted to PHP{{-code-9}code{-code-9}5} PHP has {{-code-9}code{-code-9}1}
for the replacement callback, and the pattern will be the same{{-code-9}code{-code-9}5}
If I understand you right, you want to collapse multi{-code-9}selector CSS rules and media queries into single lines{{-code-9}code{-code-9}5}
The first thing to point out is that your current pattern isn't safe for all CSS selectors{{-code-9}code{-code-9}5} It won't cover those that start with {{-code-9}code{-code-9}2}
or {{-code-9}code{-code-9}3}
, for example{{-code-9}code{-code-9}5}
Try this{-code-10}
let edited = str{{-code-9}code{-code-9}5}replace(/^{-code-11}\{{-code-9}code{-code-9}3}\{{-code-9}code{-code-9}5}{{-code-9}code{-code-9}2}{{-code-9}code{-code-9}8}{-code-10}\{-code-9}\{-code-11}]{-code-11}\s\S]+?(?=\{)/mg, match => {
return match{{-code-9}code{-code-9}5}replace(/\n/g, ' ');
});
Demo{{-code-9}code{-code-9}5}
Pattern explanation{-code-10}
- Anchor to the start of a line
- The line must start with
{{-code-9}code{-code-9}5}
,{{-code-9}code{-code-9}2}
,{{-code-9}code{-code-9}3}
,{{-code-9}code{-code-9}8}
,{-code-9}
,{-code-10}
or{-code-11}
, covering most CSS selectors{{-code-9}code{-code-9}5} - Following the selector(s), match whatever comes after, until{{-code-9}code{-code-9}5}{{-code-9}code{-code-9}5}{{-code-9}code{-code-9}5}
}
- We run each match through a callback, replacing line breaks with spaces{{-code-9}code{-code-9}5}
The m
(multi{-code-9}line) flag tells JS to interpret our anchor (^
) as pertaining to any line, not just the first{{-code-9}code{-code-9}5}
The g
(global) flag handles all instances, not just the first found{{-code-9}code{-code-9}5}