如何用& nbsp;替换HTML元素中的所有空格使用preg_replace? [英] How replace all spaces inside HTML elements with   using preg_replace?

查看:111
本文介绍了如何用& nbsp;替换HTML元素中的所有空格使用preg_replace?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在HTML元素内用& nbsp; 替换空格。
示例:

I need replace spaces with   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>


推荐答案

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

use regex to catch data between tags

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

然后将'' with '& nbsp;'

并在html之后:

also to catch before and after html :

^([^<>]*)<?

>([^<>]*)$

编辑:
go ...

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 would work without modifications (but i dont think youd understand the code ;) )

这篇关于如何用&amp; nbsp;替换HTML元素中的所有空格使用preg_replace?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆