PHP preg_replace: 如何替换 html 标签内的空格

PHP preg_replace: how to replace spaces inside html tag

我需要将标签内的空格替换为其他符号。例如:

<p class="hero big" style="color: inherit; border: none">Super big hero <br />example Yeah</p>

<p~class="hero~big"~style="color:~inherit;~border:~none">Super big hero <br~/>example Yeah</p>

我是正则表达式的新手,不知道从何入手。我可以替换所有地方的空格,但不能替换标签内的空格。

何去何从?您能否提供有效的 php 代码?

试试这个,它会用 ~

替换标签内的空格
<?php
  $data = '<p class="hero big" style="color: inherit; border: none">Super big hero <br />example Yeah</p>';
  $replace = preg_replace('/(<[^>]*)\s+([^<]*>)/', '~', $data);
  echo $replace;
?>

试试这个

$text = htmlspecialchars('<p class="hero big" style="color: inherit; border: none">Text <br />Text</p>', ENT_QUOTES);

$text = preg_replace('/\s+/', '~', $text);

echo $text;

注意:- 分开对待 html 标签和正文

感谢PHP preg_replace: how to replace text between tags?,这是一个解决方案:

<?php
$s = '<p class="hero big" style="color: inherit; border: none">Super big hero <br />example Yeah</p>';
$text = preg_replace_callback('#(<)([^>]+)(>)#', function($matches){
    return $matches[1].str_replace(" ", "~", $matches[2]).$matches[3];
}, $s);
?>

您可以使用 (*SKIP)(*F) 跳过外部标签,如下所示:

$str = preg_replace('~>[^<]*(*SKIP)(*F)|\s+~','~', $str);

See demo at eval.in