使用PHP函数将一些css添加到html中
我有三根弦使用PHP函数将一些css添加到html中,php,preg-replace,preg-match,Php,Preg Replace,Preg Match,我有三根弦 $str_a = 'style="color:red" class="abc"'; // there might be space around = $str_b = "style = 'color:green' title='text'"; $str_c = 'placeholder="no style found"'; 我想制作一个php函数,在每个函数中添加“width:100px” 如果您可以将style='…'更改为style=“…”奖励 $str_a = func($s
$str_a = 'style="color:red" class="abc"'; // there might be space around =
$str_b = "style = 'color:green' title='text'";
$str_c = 'placeholder="no style found"';
我想制作一个php函数,在每个函数中添加“width:100px”
如果您可以将style='…'
更改为style=“…”
奖励
$str_a = func($str_a); // return: style="width:100px;color:red" class="abc"
$str_b = func($str_b); // return: style="width:100px;color:green" title='text'
$str_c = func($str_c); // return: style="width:100px;" placeholder="no style found"
这是我最初的解决方案,有效,有更好的版本吗
function func($str = '') {
$str = str_replace('style =', 'style=', $str);
$str = str_replace('style =', 'style=', $str);
// if you have more than 2 space i do not care
$arr = explode('style=', $str, 2);
if ($arr[1]) {
// has style
$str1 = trim($arr[1]);
$quote = $str1[0];
$arr2 = explode($quote, substr($str1, 1), 2);
return $arr[0] . 'style="width:100px;'. $arr2[0] .'"' . $arr2[1];
} else {
return 'style="width:100px" ' . $str;
}
}
那么:
function func($str) {
if (preg_match('/style\s*=/', $str)) {
$str = preg_replace('/style\s*=\s*([\'"])([^\'"]+)\1/', 'style="width:100px;$2"', $str);
} else {
$str = 'style="width:100px;" ' . $str;
}
return $str;
}
$str_a = 'style="color:red" class="abc"'; // there might be space around =
$str_b = "style = 'color:green' title='text'";
$str_c = 'placeholder="no style found"';
echo func($str_a),"\n";
echo func($str_b),"\n";
echo func($str_c),"\n";
?>
输出:
style="width:100px;color:red" class="abc"
style="width:100px;color:green" title='text'
style="width:100px;" placeholder="no style found"
/ : regex delimiter
style : literally 'style'
\s*=\s* : equal sign with optional spaces arround
([\'"]) : group 1; a single or a double quote
([^\'"]+) : group 2; one or more any char that is not a quote
\1 : a single or a double quote (what it is i group 1)
/ : regex delimiter
说明:
style="width:100px;color:red" class="abc"
style="width:100px;color:green" title='text'
style="width:100px;" placeholder="no style found"
/ : regex delimiter
style : literally 'style'
\s*=\s* : equal sign with optional spaces arround
([\'"]) : group 1; a single or a double quote
([^\'"]+) : group 2; one or more any char that is not a quote
\1 : a single or a double quote (what it is i group 1)
/ : regex delimiter
尝试此返回preg|u replace('/(?(?=style=[''|“].*width:..['.['|“]))| style=['|“](.['.['|“])/i',“style='width:100px;$1',$str);试试这个$pattern='/(?(?=style=['|“].*宽度:.['|“])| style=['|“](.*)['|“]]/i'$替换='style=“宽度:100px;$1';echo preg_replace($pattern,$replacement,$string);嗨,raghavendra,它适用于第一个,不适用于下一个2我建议您可以使用一些字符解析并计算它们感谢Toto和解释。您是否能够更新以使第二个输出是有效的html?目前not@SIDU:抱歉,反向引用在负字符类中不起作用。看我的编辑,现在应该可以了。这太聪明了。非常感谢。