用于替换html代码中的css类的正则表达式


Regular expression for replacing css classes in html code

我正在寻找preg_replace在php中的正则表达式,它用最小化的类名替换html文件中的类名。我在css最小化过程中做到这一点。我得到了一个关联数组,类名作为键,替换项作为值。例如:

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

这些替换应该只在完全匹配的情况下进行,而不是在像'font -small-size'这样的类上进行。正则表达式是:

/"((.*[^"]?)?('} | |'}))?fonts(( '{| |'{)(.*[^"])?)?"/
使用replaceregex:
"$2$3f$5$6"

,

我得到了第二个具有替换的关联数组,这也应该用于仅从它开始的类:

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

这个替换应该在像'ui-icon- thumbup '这样的类上完成,并且应该替换为'ui- thumbup '。正则表达式是:

/"(.*)ui-icon-(.*)"/
使用replaceregex:
"$1ui-$2"

我要替换这些类名的HTML文件有以下内容:

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

这是我的一个模板文件的一个简单的小片段。正如你所看到的,我使用smarty作为模板引擎。因此,在正则表达式中也必须考虑智能语法。

在大多数情况下,替换工作得很好。我有一个问题,如果我得到一个模板文件与类属性包含相同的类两次(这可能会发生,如果我得到一个if/else-smart -block)。然后只替换其中一个。

上面的模板片段被替换为:
{if !$isSmallFontCheckDisabled}
    <span class="{if $smallFontFromCharacters}fonts t{/if}{if $hasStandardLabel} f l{/if}">
{/if}

谁可以帮助我与我的正则表达式替换所有出现的模板?

你不想使用preg_replace,你想使用preg_replace_callback()。将class属性从标记中取出,在空白处分割,处理结果数组的每个元素,然后将它们粘贴回一起。像这样…

$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
);

希望这对你有帮助。

我的用例:

为html标签的class属性添加一个额外的(css)类

演示:

https://regex101.com/r/YZ1Nre/2

正则表达式:

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

替换:

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

测试字符串:

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

结果:

 <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代码:

$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;