使用 PHP 函数将一些 css 添加到 html

use PHP function to add some css into html

我有 3 个字符串

$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*([\'"])([^\'"]+)/', 'style="width:100px;"', $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
          : a single or a double quote (what it is i group 1)
/           : regex delimiter