代码之家  ›  专栏  ›  技术社区  ›  roydukkey

php regex:如何在两个字符串之间划分空白

  •  0
  • roydukkey  · 技术社区  · 16 年前

    我一直在尝试编写一个regex,当它位于左大括号和右大括号(“”、“”)之间时,它将删除分号(“;”)后面的空白。我到了某个地方,但还没能把它拔下来。这里我有:

    <?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}';
    ?>
    

    谢谢!提前给任何愿意试一试的人。

    2 回复  |  直到 14 年前
        1
  •  0
  •   pinaki    16 年前

    您需要的是首先找到匹配项(在之间的字符串),然后对其进行操作。函数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);
    

    您可能需要对多个匹配项进行调整。

        2
  •  1
  •   cletus    16 年前

    regex对于此作业是一个坏工具,因为css不是 regular language . 如您所知,您会在属性值中遇到空白。正则表达式不理解这样的上下文。

    我想你是想缩小你的CSS。有一些工具可以做到这一点。我建议你用那些。或者得到一个可以解析CSS并以最小的空白空间输出它的库。

    如果你坚持走雷吉克斯路线,也许试试看。 Stunningly Simple CSS Minifier .

    推荐文章