php - 如何在将标签保留在 PHP (preg_replace) 中的同时替换 HTML 标签内的空格?
问题描述
假设我有这个字符串:
$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('/<(.+?)(?:»| |″)(.+?)>/', '<\1\2>', $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>'
背景故事:谷歌翻译倾向于在翻译结果中添加影响 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 演示。
但是,您可能希望创建一个模式以仅匹配 Google 翻译输出中真正使用的标签。对于a
,p
和strong
标签,它看起来像
'~<\s*(?:/\s*)?(?:p|a|strong)\s*>~u'
细节
<
-<
字符\s*
- 0+ 个空格(?:/\s*)?
- 一个可选序列,/
然后是 0+ 个空格(?:p|a|strong)
-p
或a
子strong
字符串\s*
- 0+ 个空格>
- 一个>
字符。
推荐阅读
- r - 将具有年度值的行拆分为具有月度值的行
- reactjs - 如何使用 Flow 将返回类型指定为 React 组件列表
- php - 如何使用 gotte 和 guzzle 客户端 6 发送 cookie
- c# - 如何在 Xamarin 表单滑块控件中显示刻度线
- android - gradle 发现版本错误
- javascript - 如何将值从 javascript 传递到 iOS UIWebView
- php - 重构 Eloquent Collection 以获得更好的 API 访问
- java - Seleniuim with java:获取 Excel 文件数据未在控制台上获得完整输出-
- javascript - 从成功的正则表达式中获取字符串?
- javascript - 如何使用react js检测android / ios手机中是否按下了后退按钮