【问题标题】:PHP regex replace white space by   if it is following single letter, but without breaking html tags如果它跟随单个字母,PHP 正则表达式用 替换空格,但不破坏 html 标签
【发布时间】:2017-08-15 18:02:45
【问题描述】:

我找到了here

preg_replace('/(?<=\b[a-z]) /i', '&nbsp;', $s);

处理我需要的第一部分。会变身

"hello, this is a beautiful day"

进入

"hello, this is a&nbsp;beautiful day".

不幸的是,如果它们出现在内容中,它也会破坏一些 html 标签。

"hello, this is a <a href="example.com">beautiful day</a>"

结果

"hello, this is a&nbsp;<a&nbsp;href="example.com">beautiful day</a>"

我怎样才能把这句话正则表达式成

"hello, this is a&nbsp;<a href="example.com">beautiful day</a>"

我还必须处理一些拉丁扩展字符,所以要修复的示例文本是

Dziedziczenie dlugów spadkowych jest wciąż bardzo żywym tematem, pomimo korzystnej dla spadkobierców zmiany przepisów w 2015 roku, o której szerzej pisałem na blogu <a href="http://www.prawnik-katowice.pl/blog-prawniczy/dziedziczenie-dlugow-od-18-pazdziernika-2015-roku/">tutaj</a>.

【问题讨论】:

  • 使用 DOMDocument 和 DOMXPath 并替换每个 textNode。
  • 谢谢你的这个。它可以很好地处理英文文本,但我正在处理的项目涉及一些拉丁扩展字符,这个正则表达式也匹配它们。我已经用示例文本更新了主帖。
  • 感谢更新版本。我看到它在您的示例中有效。我自己试过了,我不知道为什么它对我不起作用。你能查一下this example吗?

标签: php regex replace preg-replace


【解决方案1】:

正则表达式:

(?i)<\/?\w+[^>]*>(*SKIP)(?!)|\b(\p{Latin})\s

Live demo

PHP 代码:

preg_replace('~</?\w+[^>]*>(*SKIP)(?!)|\b(\p{Latin})\s~iu', '\\1&nbsp;', $str);

注意:注意u 修饰符。

故障

 (?i)               # Set case-insensitive flag
 <\/? \w+ [^>]* >   # Match opening / closing HTML tags 
 (*SKIP)(?!)        # Throw them away
 |                  # Or
 \b                 # Match a word-boundary position
 ( \p{Latin} )      # Capture a letter
 \s                 # Match a whitespace

【讨论】:

  • 不客气。如果它解决了您的问题,请随时将答案标记为已接受 (how to accept an answer?),如果有帮助,请投票。
猜你喜欢
  • 2011-01-06
  • 1970-01-01
  • 1970-01-01
  • 2011-11-20
  • 1970-01-01
  • 2013-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多