如何使用preg_replace匹配和添加类名?

时间:2014-04-08 03:57:59

标签: php regex preg-replace

我尝试匹配<html>代码的class属性,并使用preg_replace()添加类名。
这是我到目前为止所尝试的:

$content = '<!DOCTYPE html><html lang="en" class="dummy"><head></head><body></body></html>';
$pattern = '/< *html[^>]*class *= *["\']?([^"\']*)/i';
if(preg_match($pattern, $content, $matches)){
    $content = preg_replace($pattern, '<html class="$1 my-custom-class">', $content);
}
echo htmlentities($content);

但是,我只回来了:

<!DOCTYPE html><html class="dummy my-custom-class">"><head></head><body></body></html>

删除属性lang="en",并在标记后添加">">等重复项。请帮帮我。

2 个答案:

答案 0 :(得分:1)

删除正则表达式中的* in模式

使用此模式

/<html[^>]*class *= *["\']?([^"\']*)/i

我建议使用Dom parser来解析html

<?php
libxml_use_internal_errors(true);
$html="<!DOCTYPE html><html lang='en' class='dummy'><head></head><body></body></html>";

$dom = new DOMDocument;
$dom->loadHTML($html);


foreach ($dom->getElementsByTagName('html') as $node) {

    $node->setAttribute('class','dummy my-custom-class');

}

$html=$dom->saveHTML();
echo $html;

<强>输出

<!DOCTYPE html>
<html lang="en" class="dummy my-custom-class"><head></head><body></body></html>

答案 1 :(得分:1)

请尝试使用此代码,完美无缺:)

<?php

$content = '<!DOCTYPE html><html lang="en" class="dummy"><head></head><body></body></html>';
$pattern = '/(<html.*class="([^"]+)"[^>]*>)/i';

$callback_fn = 'process';

$content=preg_replace_callback($pattern, $callback_fn, $content);


function process($matches) {

$matches[1]=str_replace($matches[2],$matches[2]." @ My Own Class", $matches[1]);

return $matches[1];

}


echo htmlentities($content);

?>