1

简短的问题:我有一个包含 CSS 的 $css 变量,我想在该变量中找到一个给定的样式(在我的例子中是“body”那个)并用自定义样式替换它。

基本输入输出

/* blablabla */
body {
    background-color:#d0e4fe;
    font-family: 'Afamily', sanas-serif;
}
span {
    padding: 5px
}
h1 {
    color:orange;
    text-align:center;
}
body {
    margin: 10px;
    padding: 5px;
}
p {
    font-family:"Times New Roman";
    font-size:20px;
}

我们调用magicFunction():

echo magicFunction($css, 'font-color: pink; font-weight: bold;');

我们得到:

/* blablabla */
body {
    font-color: pink; font-weight: bold;
}
span {
    padding: 5px
}
h1 {
    color:orange;
    text-align:center;
}
p {
    font-family:"Times New Roman";
    font-size:20px;
}

怎么了 ?基本上我被困在这里

$bodyPattern = '/body\s\{[.|\s]*/m';
$found = preg_match_all($bodyPattern, $css, $matches);

它只发现输出的东西,如:

"body {
   '"

线路返回后......什么都没有。

当然,一旦我有了正确的正则表达式模式,我就会使用 preg_replace。

为什么要这样做:我想使用我的网站 CSS 应用CssToInlineStyle来构建时事通讯,我只想更改正文样式以避免应用某些样式(如背景颜色)。编辑:提到这一点是为了让您知道“为什么”,请随时发表评论并就此发表您的观点,但请仅将上述问题视为您应该回答的问题。

4

4 回答 4

1

我相信你之后的正则表达式是这样的: body {(([a-zA-Z0-9:;#%\(\)\'\-])*\s*)*}- 你需要为 php 中的多行正确格式化它。

您需要匹配每个角色,除了 {}确保您只捕捉身体风格而不是所有风格。

我还建议在尝试使用它之前使用这个站点来测试正则表达式。我同意其他评论,我认为你的所作所为有点疯狂……但用诺曼·贝茨的话来说,“我们有时都会有点疯狂”,我知道我有。希望这可以帮助。

编辑:

<?php
    $css = "body { \n
        color:#899890;\n
        }";
    $pattern = '/body(\s){0,1}{(([a-zA-Z0-9:;#%\(\)\'\-])*\s*)*}/m';
    $found = preg_match_all($pattern, $css, $matches);

    print_r($matches);
?>

产生:

Array
(
    [0] => Array
        (
            [0] => body { 

        color:#899890;

        }
        )

    [1] => Array
        (
            [0] =>  
        )

    [2] => Array
        (
            [0] => 
        )

    [3] => Array
        (
            [0] => ;
        )

)

它似乎对我有用。

于 2012-09-20T11:55:48.180 回答
0

避免需要这样做的一种方法是利用 CSS 的级联功能:

body {
    background-color:#d0e4fe;
    font-family: 'Afamily', sanas-serif;
}

<? if (...): ?>
    body {
        // overrides the definitions applied above
        background-color: inherit;
        font-family: inherit;

        // and define your own rules
        font-color: pink; 
        font-weight: bold;
    }
<? endif; ?>
于 2012-09-21T16:34:27.730 回答
0

我会像这样使用css。

<style>
<? include style.php;?>
</style>

现在在 style.php

body { <? magicFunction('font-color: pink; font-weight: bold;');
?> 
}

h1 {
    color:orange;
    text-align:center;
}
p {
    font-family:"Times New Roman";
    font-size:20px;
}

而magicFunction 会是这样的

function magicFunction($style) {
    echo $style;
}
于 2012-09-20T11:29:52.317 回答
0

可以使用 PHP 提供您的 CSS 文件。或者你使用类似SASS的东西在你的 CSS 中使用变量。

使用 PHP 解析 CSS 并使用正则表达式替换变量将导致性能非常差,并给您的服务器带来很大的负载。

于 2012-09-20T11:05:42.453 回答