I have 3 strings
$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"';
and I'd like make a php function to add "width:100px"
into each of them
if you can change style='...'
tostyle="..."
a bonus
$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"
This is my original solution, working, is there any better version?
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;
}
}
How about:
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";
?>
Output:
style="width:100px;color:red" class="abc"
style="width:100px;color:green" title='text'
style="width:100px;" placeholder="no style found"
Explanation:
/ : 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