【问题标题】:preg_replace() tags namepreg_replace() 标签名称
【发布时间】:2018-03-13 18:29:05
【问题描述】:

我有很多标签的 CSS 文件,一些字符串:

p{
    margin:10px 0;
    padding:0;
}
h1,h2,h3,h4,h5,h6{
    display:block;
    margin:0;
    padding:0;
}

我想得到这个:

#content p{
        margin:10px 0;
        padding:0;
    }

#content h1,
#content h2,
#content h3,
#content h4,
#content h5,
#content h6{
        display:block;
        margin:0;
        padding:0;
    }

我尝试像这样查找:([^\n|,{]*\n+) 但获取标签正文,但没有标签名称。 我怎么想 - 我需要找到 }\n,

【问题讨论】:

    标签: php css regex laravel preg-replace


    【解决方案1】:

    preg_replace_callback是你的朋友:

    $css = <<<EOD
    p{
        margin:10px 0;
        padding:0;
    }
    h1,h2,h3,h4,h5,h6{
        display:block;
        margin:0;
        padding:0;
    }
    EOD;
    
    $result = preg_replace_callback(
        '/\n?([\w,\h]+)(?=\{)/',
        function ($m) {
            $l = preg_replace('/\w+\h*,?/', "#content $0\n",$m[0]);
            return $l;
        },
        $css
    );
    echo $result;
    

    输出:

    #content p
    {
        margin:10px 0;
        padding:0;
    }
    #content h1,
    #content h2,
    #content h3,
    #content h4,
    #content h5,
    #content h6
    {
        display:block;
        margin:0;
        padding:0;
    }
    

    说明:

    \n?         : optional linefeed
    (           : start group 1
      [\w,\h]+  : 1 or more word character or horizontal space
    )           : end group
    (?=\{)      : positive lookahead, make sure we have a curly brace after
    

    第二个正则表达式:

    \w+         : 1 or more word character
    \h*         : 0 or more horizontal space
    ,?          : optional comma
    

    【讨论】:

      猜你喜欢
      • 2016-09-18
      • 1970-01-01
      • 2021-05-28
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 2019-10-27
      • 1970-01-01
      • 2013-12-29
      相关资源
      最近更新 更多