如何在将标签保留在 PHP (preg_replace) 的同时替换 HTML 标签内的空格?

How to replace spaces inside of HTML tags while keeping the tags in PHP (preg_replace)?

假设我有这个字符串:

$string = '<p > ¡Esto es una prueba! < /p > <p> <strong > Prueba 123 </strong> </p> <p> <strong> < a href="https://matricom.net"> MATRICOM < / a> </ strong> </p> <p> <strong > Todas las pruebas aquí ... </strong > < /p>'

我想做的是使用 PHP 修复 HTML 标签(由于空格,它们的格式不正确)。我尝试了几种在网上找到的不同的正则表达式,例如:

$html = trim(preg_replace('/<\s+>/', '<>', $text));

和:

$html = preg_replace('/<(.+?)(?:»| |″)(.+?)>/', '<>', $text);

我正在尝试获得这样的字符串输出(在 HTML 标签的前部和尾部删除空格):

'<p> ¡Esto es una prueba! </p> <p> <strong> Prueba 123 </strong> </p> <p> <strong> <a href="https://matricom.net"> MATRICOM </a> </strong> </p> <p> <strong> Todas las pruebas aquí ... </strong> </p>'

背景故事:Google Translate 倾向于在翻译结果中添加随机空格,这会影响 HTML 结构。只是在寻找一种快速清理标签的方法。我已经搜索了两天如何执行此操作,但似乎找不到完全符合我正在寻找的东西。

在大多数情况下,您可以使用 preg_replace_callback 解决方案:

$text='<p > ¡Esto es una prueba! < /p > <p> <strong > Prueba 123 </strong> </p> <p> <strong> <a href="https://matricom.net"> MATRICOM < / a> </ strong> </p> <p> <strong > Todas las pruebas aquí ... </strong > < /p>';
echo preg_replace_callback('~<[^<>]+>~u', function($m) { 
    return str_replace(' ', '', $m[0]); 
  // or,  preg_replace('~\s+~u', '', $m[0]); 
}, $text);

参见PHP demo

但是,您可能希望创建一个模式以仅匹配 Google 翻译输出中真正使用的标签。对于 apstrong 标签,它看起来像

'~<\s*(?:/\s*)?(?:p|a|strong)\s*>~u'

this regex demo

详情

  • < - < 字符
  • \s* - 0+ 个空格
  • (?:/\s*)? - / 的可选序列,然后是 0+ 个空格
  • (?:p|a|strong) - pastrong 子串
  • \s* - 0+ 个空格
  • > - 一个 > 字符。

这可能超出您的需要,但翻译 HTML 文件的过程(无论是机器翻译还是人工翻译)涉及通过过滤器解析 HTML hides\protects HTML标签完全由编译过程。翻译编辑器只允许出于语言目的移动某些标签(在您的示例中可能是 href)。此外,在某些语言中,可能不需要粗体格式。

post 处理后 HTML 保持不变,只是文本内容发生了变化。

请注意,您可能会发现 Google 翻译 HTML 标签的内容有时也会被翻译,这会给您带来各种问题。

我可以更详细地解释解决方案,如果您对此感兴趣,请告诉我。所需的工具可以免费获得。