只替换开始HTML标记内不需要的字符


Replace unwanted characters inside opening HTML tag only

我需要在脚本中做一个小修复。

我需要2个特定的字符(»)在打开iframe标签内被更改为双引号(")。

例如:

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

它的意思是:

<“> 

将被quote代替。来自其他网站的工作示例:

$content = preg_replace('/<([^<>]+)>/e', '"<" .str_replace(""", ''"'', "$1").">"', $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
    );

要替换开始iframe标记中的一个或多个流氓多字节字符(以不了解html的方式),可以在preg_replace_callback()中调用strtr()str_replace()。(演示)

echo preg_replace_callback(
         '/<[^>]+>/',
         fn($m) => strtr($m[0], ['»' => '"', '“' => '"']),
         $tests
     );

echo preg_replace_callback(
         '/<[^>]+>/',
         fn($m) => str_replace(['»', '“'], '"', $m[0]),
         $tests
     );

因为HTML是"坏的"/无效的,所以可能不值得尝试使用适当的DOM解析器来纠正标记。

应该可以了

$content = preg_replace('/<(.+?)(?:»|“|″)(.+?)>/','<'1"'2>', $content);

一个单一的regexp,匹配任何包含»之间的<>。替换为'1(第一个捕获组)。和'2(第二捕获组)。

希望能有所帮助

一个解决方案是不使用preg_replace。如果格式与您在问题中描述的一样,您可以简单地使用str_replace。

$str = '<iframe src=»http://test.test″>»hellohello»</iframe>';
$repl = str_replace(array('=»', '″>', '″/>'), array('"', '">'), $str);
print_r($repl);