How to replace all spaces inside HTML elements with using preg_replace?

I need to replace spaces  inside HTML elements. Example:

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

should become

<table atrr="zxzx"><tr>
<td>adfa&nbsp;a&nbsp;&nbsp;&nbsp;adfadfaf></td><td><br />&nbsp;dfa&nbsp;&nbsp;dfa</td>
</tr></table>
+3
source share
3 answers

use regex to capture data between tags

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

then replace ' 'with'&nbsp;'

also catch before and after html:

^([^<>]*)<?

>([^<>]*)$

Edit: here you go ....

<?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, create_function('$matches','return $matches[1].str_replace(" ","&nbsp;",$matches[2]);'), $data);
$data = preg_replace_callback($ex1, create_function('$matches','return str_replace(" ","&nbsp;",$matches[1]).$matches[2];'), $data);
$data = preg_replace_callback($ex2, create_function('$matches','return $matches[1].str_replace(" ","&nbsp;",$matches[2]);'), $data);

echo $data;
?>

it works ... slightly modified, but it will work unchanged (but I don't think you understand the code;))

+3
source

If you work with php, you can do

$content = str_replace(' ', '&nbsp;', $content);
+6
source

Since HTML tokenization with regular expressions can be quite complicated (especially when resolving SGML quirks), you should use an HTML DOM parser such as the PHP DOM library . Then you can query the DOM, get all the text nodes and apply your replace function on it:

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

A function mapOntoTextNodesis a custom function that I defined in How to replace text URLs and exclude URLs in HTML tags?

+3
source

Source: https://habr.com/ru/post/1796626/


All Articles