Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/248.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用正则表达式和PHP选择和替换字符串中的HTML属性?_Php_Regex - Fatal编程技术网

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

如何使用正则表达式和PHP选择和替换字符串中的HTML属性?,php,regex,Php,Regex,我想换衣服 {"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;' >F

我想换衣服

{"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>"}
PHPFiddle链接:

没有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));

PHPFiddle链接:

这是一个json字符串吗?是的,它是一个断了的字符串。B,谢谢,这很有魅力;不客气。请点击upvote按钮旁边的勾号接受我的回答: