php - 如何在不删除标签的情况下替换 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 结构的随机空格。只是寻找一种快速清理标签的方法。我已经搜索了两天如何做到这一点,似乎找不到任何适合我正在寻找的东西。
解决方案
这就是我想出的。适用于您的字符串
< *(\/*) *(.+?) *>
< Matches a < char
* Matches zero or more spaces. There is a ' ' (space) before *
(\/*) Matches zero or more / () indicates capturing group 1
* Matches zero or more. Do notice the ' ' before *
( Start of capturing group 2
.+ Matches any character except a line break
? Lazy Matching
) End of capturing group 2
* Matches zero or more spaces. Again a ' ' before *
> Matches a > char
然后像
$cleaned = preg_replace('/< *(\/*) *(.+?) *>/', '<\1\2>', $html);
echo $cleaned;
# input 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>';
# Cleaned 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>
这将从这些格式中删除空格
< div > </ div > < / div > < div class="myclass" >
但它不会删除属性中的空格。所以这
< div class = " myclass " >
将被转换为<div class = " myclass ">
. 但是属性中的空格是允许的(即使不推荐)
如果我错过了一个案例,请告诉我,我会尝试合并。
推荐阅读
- javascript - 限制字符被添加到 JS 中的元素
- python - 有没有办法组合(连接)一列的不同值?
- javascript - 如何阻止 Json.Parse() 实例化在字符串化对象中找到的类?
- c# - C# 反序列化缺少标签的 XML
- tensorflow - KerasLayer vs tf.keras.applications 性能
- authentication - 登录使用任何密码对用户进行身份验证
- python-3.x - 如何使单选按钮连接到文本文件中的一行并使其显示在框架上
- javascript - React 组件:需要格式化来自 API 响应的地址并将其传递给具有复制到剪贴板功能的组件
- python - cursor.fetchone() 尝试插入后返回 None?
- python - 在读/写时保留文本格式以塑造文本python pptx