如何使用正则表达式和PHP选择和替换字符串中的HTML属性


How to select and replace HTML attributes in string using regex and PHP?

我想更改

{"name":"column","content":"<h3 class="open-sans" style="font-size: 2em; line-height:2em;" >FORM TITLE</h3>"}

对此(用单引号替换HTML属性的双引号)

{"name":"column","content":"<h3 class='open-sans' style='font-size: 2em; line-height:2em;' >FORM TITLE</h3>"}

我们非常感谢您的帮助。

Aaaa答案是:

$count = null;
$subject = '{"name":"column","content":"<h3 class="open-sans" style="font-size: 2em; line-height:2em;" >FORM TITLE</h3>"}';
$result = preg_replace('/="(.*?)"/s', '=''$1''', $subject, -1, $count);
print_r(htmlspecialchars($subject) . "<br />");
print_r(htmlspecialchars($result));

输出:

{"name":"column","content":"<h3 class="open-sans" style="font-size: 2em; line-height:2em;" >FORM TITLE</h3>"}
{"name":"column","content":"<h3 class='open-sans' style='font-size: 2em; line-height:2em;' >FORM TITLE</h3>"}

PHP隐藏链接:http://phpfiddle.org/main/code/5g33-8k4f

没有regex的替代解决方案(有点难看,但对于新手来说可能更容易理解):

$string = '{"name":"column","content":"<h3 class="open-sans" style="font-size: 2em; line-height:2em;" >FORM TITLE</h3>"}';
$array = explode('="', $string);
array_shift($array);
foreach ($array as $value) {
    $temp = explode('"', $value);
    $search = '"' . $temp[0] . '"';
    $replace = "'" . $temp[0] . "'";
    $string = str_replace($search, $replace, $string);
}
print_r(htmlspecialchars($string));

PHP隐藏链接:http://phpfiddle.org/main/code/ksqm-gu1r