简体   繁体   English

用于替换HTML代码中CSS类的正则表达式

[英]Regular expression for replacing css classes in html code

I am looking for a regular expression for preg_replace in php which replaces class-names in html files with minified classnames. 我在php中寻找preg_replace的正则表达式,用最小的类名替换html文件中的类名。 I do this in a css-minifying process. 我这样做是在最小化CSS的过程中进行的。 I got an associative array with the class-names as keys and the replacements as values. 我得到了一个关联数组,其中类名作为键,替换项作为值。 Ie: 即:

$myReplacements = array('fonts' => 'f', 'label' => 'l', 'tiny' => 't')

These replacements should only be done on exact match, but not on a class like 'fonts-small-size'. 这些替换只能在完全匹配的情况下进行,而不能在“ fonts-small-size”之类的类上进行。 My regular expression for that is: 我的正则表达式是:

/"((.*[^"]?)?(\} | |\}))?fonts(( \{| |\{)(.*[^"])?)?"/

with the replaceregex: 使用replaceregex:

"$2$3f$5$6"

-- -

I got a second associative array with replacements which should be done also for classes only starting with it: 我得到了带有替换的第二个关联数组,对于仅以它开头的类也应该这样做:

$forcedReplacements = array('ui-icon-' => 'ui-')

This replacements should be done on classes like 'ui-icon-thumbs-up' and should be replaced with 'ui-thumbs-up'. 此替换应在“ ui-icon-thumbs-up”之类的类上进行,并应替换为“ ui-thumbs-up”。 My regular expression for that is: 我的正则表达式是:

/"(.*)ui-icon-(.*)"/

with the replaceregex: 使用replaceregex:

"$1ui-$2"

The HTML file i want to replace this class names in has the following content: 我要替换此类名称的HTML文件具有以下内容:

{if !$isSmallFontCheckDisabled}
    <span class="{if $smallFontFromCharacters}fonts tiny{/if}{if $hasStandardLabel} fonts label{/if}">
{/if}

This is a small simple snippet of one of my template files. 这是我的模板文件之一的小片段。 As you can see i use smarty as template engine. 如您所见,我将smarty用作模板引擎。 So, also the smarty syntax has to be considered in my regular expression. 因此,在我的正则表达式中也必须考虑聪明的语法。

In most cases the replacements work pretty good. 在大多数情况下,替换产品效果很好。 I have a problem if i got a template file with the class attribute containing the same class twice (This may happen if i got a if/else-smarty-block). 如果我的模板文件的class属性包含两次相同的类,就会出现问题(如果我得到了if / else-smarty-block,可能会发生这种情况)。 Then only one of the two is replaced. 然后,仅替换其中之一。

The template snippet above is replaced to: 上面的模板代码段被替换为:

{if !$isSmallFontCheckDisabled}
    <span class="{if $smallFontFromCharacters}fonts t{/if}{if $hasStandardLabel} f l{/if}">
{/if}

May anyone help me with my regular expression for replacing all occurences of the templates? 有人可以用我的正则表达式来帮助我替换所有出现的模板吗?

You don't want to use preg_replace, you want to use preg_replace_callback(). 您不想使用preg_replace,而是想使用preg_replace_callback()。 Pull the class attribute out of the tag, split on whitespace, process each element of the resulting array and then paste it back together. 将class属性从标记中拉出,在空白处分割,处理结果数组的每个元素,然后将其粘贴回去。 Something like this... 像这样

$line = preg_replace_callback(
    '/(<[^<] class=\")([^"]*)(\")/',
    function ($matches) {
        $classes = explode(' ', $matches[2])
            /*
                Do your class name replacements here
            */
        return $matches[1].(implode(' ', $classes)).$matches[3];
    },
    $line
);

Hope this helps... 希望这可以帮助...

My use case: 我的用例:

Append an additional (css) class to the class attribute for an html tag 将附加(css)类附加到html标签的class属性

Demo: https://regex101.com/r/YZ1Nre/2 演示: https : //regex101.com/r/YZ1Nre/2

Regex: 正则表达式:

/(?<opening_tag><input)(?<attributes_before_class>.*)(?<class_attribute_start>class=\')(?<class_value>.*?)(?<class_attribute_end>\')(?<attributes_after_class>.*)(?<closing_tag>\/>)/

Substitution: 替代:

${opening_tag}${attributes_before_class}${class_attribute_start}${class_value} uk-width-1-1 ${class_attribute_end}${attributes_after_class}${closing_tag}

Test String: 测试字符串:

  <input name='input_4' id='input_2_4' type='text' value='' class='large'  tabindex='1'   aria-required="true" aria-invalid="true" />

Result: 结果:

 <input name='input_4' id='input_2_4' type='text' value='' class='large uk-width-1-1'  tabindex='1'   aria-required="true" aria-invalid="true" />


PHP Code: PHP代码:

$re = '/(?<opening_tag><input)(?<attributes_before_class>.*)(?<class_attribute_start>class=\')(?<class_value>.*?)(?<class_attribute_end>\')(?<attributes_after_class>.*)(?<closing_tag>\/>)/';
$str = 'Your test string here';
$new_css_class = 'uk-width-1-1';

$subst = '${opening_tag}${attributes_before_class}${class_attribute_start}${class_value} '.$new_css_class.' ${class_attribute_end}${attributes_after_class}${closing_tag}';

// if the named group replacing doesnt work, just use the indices as references
//$subst = '${1}${2}${3}${4} uk-width-1-1 ${5}${6}${7}';

$result = preg_replace($re, $subst, $str);

echo "The result of the substitution is ".$result;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM