正则 html 去掉多余的空格
时间: 2023-05-20 14:05:06 浏览: 71
可以使用正则表达式来去掉多余的空格,具体的正则表达式如下:
```html
preg_replace('/\s+/', ' ', $html);
```
其中,`$html` 是需要处理的 HTML 代码,`preg_replace` 是 PHP 中的一个函数,用于替换字符串中的匹配项。`\s+` 表示匹配一个或多个空格,用空格替换即可去掉多余的空格。
相关问题
正则 让html 成一行 没多余的
空格、换行符等
可以使用正则表达式将HTML代码中的空格、换行符等无用符号去掉,将HTML代码压缩成一行。具体的正则表达式如下:
```javascript
html.replace(/[\n\r\s]+/g, '')
```
其中,`/[\n\r\s]+/g`表示匹配所有的空格、换行符等符号,将其替换为空字符串。使用`replace`函数将HTML代码中的空格、换行符等符号替换为空字符串即可。
示例代码:
```javascript
var html = '<html>\n\t<head>\n\t\t<title>Test</title>\n\t</head>\n\t<body>\n\t\t<h1>Hello World!</h1>\n\t</body>\n</html>';
var compressedHtml = html.replace(/[\n\r\s]+/g, '');
console.log(compressedHtml);
```
输出结果:
```
<html><head><title>Test</title></head><body><h1>HelloWorld!</h1></body></html>
```
正则 html 格式话
可以使用正则表达式来格式化 HTML,以下是一个示例:
```python
import re
def format_html(html):
# 去除多余的空格和换行符
html = re.sub(r'\s+', ' ', html)
# 添加缩进
html = re.sub(r'<', '\n<', html)
html = re.sub(r'</', '\n</', html)
# 去除连续的换行符
html = re.sub(r'\n+', '\n', html)
return html.strip()
# 示例用法
html = '<html><head><title>Test</title></head><body><p>Hello, world!</p></body></html>'
formatted_html = format_html(html)
print(formatted_html)
```
输出结果:
```
<html>
<head>
<title>Test</title>
</head>
<body>
<p>Hello, world!</p>
</body>
</html>
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)