[英]Replace multiple ' ' with HTML tag
Working on a strange one today - A client will be pasting in a load of text to an HTML editor which adds many non breaking spaces. 今天在一个奇怪的工作 - 一个客户端将粘贴到HTML编辑器的大量文本中,这会添加许多不间断的空格。 I need to style this when output to the browser.
输出到浏览器时我需要设置样式。
I am trying to make the following string 我正在尝试制作以下字符串
<ul class="columns">
<li><u>Running costs</u></li>
<li>Urban mpg 50.4 mpg</li>
<li>Extra Urban mpg 72.4 mpg</li>
</ul>
Change to this: 改为:
<ul class="columns">
<li><u>Running costs</u></li>
<li>Urban mpg<span class="right">50.4 mpg</span></li>
<li>Extra Urban mpg<span class="right">72.4 mpg</span></li>
</ul>
Using preg replace or an HTML parser. 使用preg替换或HTML解析器。 I have tried both.
我试过了两个。 My PHP preg_replace is this:
我的PHP preg_replace是这样的:
preg_replace("/( )/", "<span>", $input_lines);
Which replaces all &nspb;'s with . 这取代了所有&nspb;的。 I only want the one span to be added and I need it to close at the end too.
我只希望添加一个跨度,我也需要它在最后关闭。 I have been experminting with Simple HTML Dom but not sure what functions to use to best achieve this.
我一直在使用Simple HTML Dom,但不确定使用哪些函数来实现这一目标。
Thanks 谢谢
You could try 你可以试试
(?: )+([^<]*)
Replace with 用。。。来代替
<span class="right">\1</span>
It matches all repeating
它匹配所有重复的
, and then grabs everything up to <
of the closing tag. ,然后将所有内容抓取到结束标记的
<
。 Replacing it with the above string inserts the capture with the surrounding span
. 用上面的字符串替换它会将捕获与周围的
span
一起插入。
You could use a css selector, you'd need the escaped unicode value. 您可以使用css选择器,您需要转义的unicode值。
span.right::before {
content: "\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0";
}
This should work. 这应该工作。
<?php
$text = '<ul class="columns">
<li><u>Running costs</u></li>
<li>Urban mpg 50.4 mpg</li>
<li>Extra Urban mpg 72.4 mpg</li>
</ul>';
$new_text = preg_replace("/(?: )+([^<]*)/", " <span class=\"right\">\${1}</span>", $text);
echo $new_text;
Result: https://eval.in/600085 结果: https : //eval.in/600085
Try this 尝试这个
<?php
$text = "<ul class='columns'>
<li><u>Running costs</u></li>
<li>Urban mpg 50.4 mpg</li>
<li>Extra Urban mpg 72.4 mpg</li>
</ul>";
echo $text;
$pattern = '/( )+([\w\.\s]+)(<\/li>)/';
$text = preg_replace($pattern,'<span class="name">$2</span>', $text);
echo htmlspecialchars($text);
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.