如何使用preg_replace替换HTML元素中的所有空格?

问题描述 投票:5回答:3

我需要在HTML元素中用 替换空格。例:

<table atrr="zxzx"><tr>
<td>adfa a   adfadfaf></td><td><br /> dfa  dfa</td>
</tr></table>

应该成为

<table atrr="zxzx"><tr>
<td>adfa&nbsp;a&nbsp;&nbsp;&nbsp;adfadfaf></td><td><br />&nbsp;dfa&nbsp;&nbsp;dfa</td>
</tr></table>
php html preg-replace spaces
3个回答
4
投票

使用正则表达式来捕获标记之间的数据

(?:<\/?\w+)(?:\s+\w+(?:\s*=\s*(?:\".*?\"|'.*?'|[^'\">\s]+)?)+\s*|\s*)\/?>([^<]*)?

然后用' '取代'&nbsp;'

还要在html之前和之后捕获:

^([^<>]*)<?

>([^<>]*)$

编辑:你去吧....

<?php
$data="dasdad asd a  <table atrr=\"zxzx\"><tr><td>adfa a   adfadfaf></td><td><br /> dfa  dfa</td></tr></table>  asdasd s ";
$exp="/((?:<\\/?\\w+)(?:\\s+\\w+(?:\\s*=\\s*(?:\\\".*?\\\"|'.*?'|[^'\\\">\\s]+)?)+\\s*|\\s*)\\/?>)([^<]*)?/";

$ex1="/^([^<>]*)(<?)/i";
$ex2="/(>)([^<>]*)$/i";

$data = preg_replace_callback($exp, function ($matches) {
    return $matches[1] . str_replace(" ", "&nbsp;", $matches[2]);
}, $data);
$data = preg_replace_callback($ex1, function ($matches) {
    return str_replace(" ", "&nbsp;", $matches[1]) . $matches[2];
}, $data);
$data = preg_replace_callback($ex2, function ($matches) {
    return $matches[1] . str_replace(" ", "&nbsp;", $matches[2]);
}, $data);

echo $data;
?>

它的工作原理......略有修改,但它可以不经修改地工作(但我不认为你理解代码;))


8
投票

如果你正在使用php,你可以这样做

$content = str_replace(' ', '&nbsp;', $content);

3
投票

由于使用正则表达式对HTML进行标记可能非常复杂(特别是在允许SGML怪癖时),您应该使用像PHP’s DOM library那样的HTML DOM解析器。然后,您可以查询DOM,获取所有文本节点并在其上应用替换函数:

$doc = new DOMDocument();
$doc->loadHTML($str);
$body = $doc->getElementsByTagName('body')->item(0);
mapOntoTextNodes($body, function(DOMText $node) { $node->nodeValue = str_replace(' ', '&nbsp;', $node->nodeValue); });

mapOntoTextNodes function是我在How to replace text URLs and exclude URLs in HTML tags?中定义的自定义函数

© www.soinside.com 2019 - 2024. All rights reserved.