2010-03-19 74 views
0

我一直在嘗試編寫一個正則表達式,它將在分號(';')之後刪除空格,當它位於打開和關閉大括號('{',' }「)。我已經到了某個地方,但一直未能完成。在這裏我已經有了:PHP正則表達式:如何在兩個字符串之間劃分空白

<?php 
$output = '@import url("/home/style/nav.css"); 
body{color:#777; 
background:#222 url("/home/style/nav.css") top center no-repeat; 
line-height:23px; 
font-family:Arial,Times,serif; 
font-size:13px}' 
$output = preg_replace("#({.*;) \s* (.*[^;]})#x", "$1$2", $output); 
?> 

的的$輸出應該如下。另外請注意,字符串中的第一個分號仍然跟着空格,因爲它應該是。

<?php 
$output = '@import url("/home/style/nav.css"); 
body{color:#777;background:#222 url("/home/style/nav.css") top center no-repeat;line-height:23px;font-family:Arial,Times,serif;font-size:13px}'; 
?> 

謝謝!提前給任何願意給它一個機會的人。

回答

0

你需要的是首先找到匹配({}之間的字符串),然後對其進行操作。函數preg_replace_callback()應該爲你做的伎倆:

function replace_spaces($str){ 
     $output = preg_replace('/(;[[:space:]]+)/s', ';', $str[0]); 
     return $output; 
} 

$output = '@import url("/home/style/nav.css"); 
body{color:#777; 
background:#222 url("/home/style/nav.css") top center no-repeat; 
line-height:23px; 
font-family:Arial,Times,serif; 
font-size:13px}'; 
$out = preg_replace_callback("/{(.*)}/s", 'replace_spaces', $output); 

您可能需要調整此多個匹配。

+0

非常感謝你,這正是我所需要的。 – roydukkey 2010-03-20 03:04:17

+0

可能會考慮放棄;)... – pinaki 2010-04-05 14:39:04

1

正則表達式是這項工作的壞工具,因爲CSS不是regular language。如您所知,您會在房產價值中遇到空白區域。正則表達式不理解這樣的上下文。

我假設你正試圖縮小你的CSS。有這方面的工具。我會建議使用這些。要麼是得到一個解析CSS的庫,並且可以用最小的空白來輸出它。

如果你堅持走正則表達式的路線,也許試試Stunningly Simple CSS Minifier

相關問題