PHP preg_replace HTML 标签内的所有引号
PHP preg_replace all quotes inside HTML tag
我需要在脚本中做一些修复,但我不擅长 preg_replace。我相信这对你们中的许多人来说会很容易。
我需要 HTML 标签内的 3 个特定引号或所有引号,如下所示:“
例如:
<iframe src=»http://test.test″>»hellohello»</iframe>
需要变成:<iframe src="http://test.test">»hellohello»</iframe>
到目前为止我的代码:
$content = preg_replace("/\<[“]\>/","\"",$content);
$content = preg_replace("/\<[»]\>/","\"",$content);
$content = preg_replace("/\<[″]\>/","\"",$content);
没用…
感谢您的帮助!!
这应该可以解决问题
$content = preg_replace('/<(.+?)(?:»|“|″)(.+?)>/','<">', $content);
一个正则表达式,匹配 <
和 >
之间包含 »
或 “
或 ″
的任何内容。
替换为 </code>(第一个捕获组)。接着是 " 和 <code>
(第二个捕获组)。
希望对你有帮助
你里面的正则表达式有误。
$content = preg_replace("/\<[“]\>/","\"",$content);
它的意思是:
<“>
将替换为引号。
来自其他站点的工作示例:
$content = preg_replace('/<([^<>]+)>/e', '"<" .str_replace(""", \'"\', "").">"', $content);
此处使用 str_replace,您可以在那里传递任何引号。
你应该对 preg_replace_callback 做同样的事情,它推荐用于更新的 PHP 版本(从 5.5 /e 标志被弃用)。
示例(不确定它是否有效,但你明白了):
preg_replace_callback(
'/<([^<>]+)>/',
function ($matches) {
return str_replace('OldQuote', 'NewQuote',$matches[0]);
},
$content
);
或者用许多不同的引号创建数组:
preg_replace_callback(
'/<([^<>]+)>/',
function ($matches) {
$quotes = array('OldQuote'=>'NewQuote','OldQuote2'=>'NewQuote2');
return str_replace(array_keys($quotes), array_values($quotes),$matches[0]);
},
$content
);
一种解决方案是不使用 preg_replace。
如果格式如您所描述的那样,您可以简单地使用 str_replace。
$str = '<iframe src=»http://test.test″>»hellohello»</iframe>';
$repl = str_replace(array('=»', '″>', '″/>'), array('"', '">'), $str);
print_r($repl);
我需要在脚本中做一些修复,但我不擅长 preg_replace。我相信这对你们中的许多人来说会很容易。
我需要 HTML 标签内的 3 个特定引号或所有引号,如下所示:“
例如:
<iframe src=»http://test.test″>»hellohello»</iframe>
需要变成:<iframe src="http://test.test">»hellohello»</iframe>
到目前为止我的代码:
$content = preg_replace("/\<[“]\>/","\"",$content);
$content = preg_replace("/\<[»]\>/","\"",$content);
$content = preg_replace("/\<[″]\>/","\"",$content);
没用…
感谢您的帮助!!
这应该可以解决问题
$content = preg_replace('/<(.+?)(?:»|“|″)(.+?)>/','<">', $content);
一个正则表达式,匹配 <
和 >
之间包含 »
或 “
或 ″
的任何内容。
替换为 </code>(第一个捕获组)。接着是 " 和 <code>
(第二个捕获组)。
希望对你有帮助
你里面的正则表达式有误。
$content = preg_replace("/\<[“]\>/","\"",$content);
它的意思是:
<“>
将替换为引号。 来自其他站点的工作示例:
$content = preg_replace('/<([^<>]+)>/e', '"<" .str_replace(""", \'"\', "").">"', $content);
此处使用 str_replace,您可以在那里传递任何引号。 你应该对 preg_replace_callback 做同样的事情,它推荐用于更新的 PHP 版本(从 5.5 /e 标志被弃用)。 示例(不确定它是否有效,但你明白了):
preg_replace_callback(
'/<([^<>]+)>/',
function ($matches) {
return str_replace('OldQuote', 'NewQuote',$matches[0]);
},
$content
);
或者用许多不同的引号创建数组:
preg_replace_callback(
'/<([^<>]+)>/',
function ($matches) {
$quotes = array('OldQuote'=>'NewQuote','OldQuote2'=>'NewQuote2');
return str_replace(array_keys($quotes), array_values($quotes),$matches[0]);
},
$content
);
一种解决方案是不使用 preg_replace。 如果格式如您所描述的那样,您可以简单地使用 str_replace。
$str = '<iframe src=»http://test.test″>»hellohello»</iframe>';
$repl = str_replace(array('=»', '″>', '″/>'), array('"', '">'), $str);
print_r($repl);