3

我试图在每个分号后插入一个空格,除非分号是 HTML 实体的一部分。这里的例子很短,但我的字符串可能很长,有几个分号(或没有分号)。

Coca‑Cola =>     Coca‑Cola  (‑ is a non-breaking hyphen)
Beverage;Food;Music => Beverage; Food; Music

我发现以下正则表达式可以解决短字符串的问题:

<?php
$a[] = 'Coca&#8209;Cola';
$a[] = 'Beverage;Food;Music';
$regexp = '/(?:&#?\w+;|[^;])+/';
foreach ($a as $str) {
    echo ltrim(preg_replace($regexp, ' $0', $str)).'<br>';
}
?>

但是,如果字符串有点大,preg_replace上面的内容实际上会使我的 Apache 服务器崩溃(在页面加载时重置了与服务器的连接。)将以下内容添加到上面的示例代码中:

$a[] = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. '.
   'In blandit metus arcu. Fusce eu orci nulla, in interdum risus. '.
   'Maecenas ut velit turpis, eu pretium libero. Integer molestie '.
   'faucibus magna sagittis posuere. Morbi volutpat luctus turpis, '.
   'in pretium augue pellentesque quis. Cras tempor, sem suscipit '.
   'dapibus lacinia, dolor sapien ultrices est, eget laoreet nibh '.
   'ligula at massa. Cum sociis natoque penatibus et magnis dis '.
   'parturient montes, nascetur ridiculus mus. Phasellus nulla '.
   'dolor, placerat non sem. Proin tempor tempus erat, facilisis '.
   'euismod lectus pharetra vel. Etiam faucibus, lectus a '.
   'scelerisque dignissim, odio turpis commodo massa, vitae '.
   'tincidunt ante sapien non neque. Proin eleifend, lacus et '.
   'luctus pellentesque;odio felis.';

上面的代码(带有大字符串)使 Apache 崩溃,但如果我在命令行上运行 PHP,它就可以工作。

在我的程序的其他地方,我preg_replace在更大的字符串上使用没有问题,所以我猜测正则表达式中的某些东西压倒了 PHP/Apache。

那么,有没有办法“修复”正则表达式,以便它可以在具有大字符串的 Apache 上工作,或者是否有另一种更安全的方法来做到这一点?

我在 Windows XP SP3 上使用 PHP 5.2.17 和 Apache 2.0.64,如果有帮助的话。(不幸的是,现在升级 PHP 或 Apache 不是一个选项。)

4

3 回答 3

2

我会建议这个匹配表达式:

\b(?<!&)(?<!&#)\w+;

...匹配一系列字符(字母、数字和下划线),这些字符前面没有 & 符号(或 & 符号后跟井号),但后跟分号。

它分解为:

\b          # assert that this is a word boundary
(?<!        # look behind and assert that you cannot match
 &          # an ampersand
)           # end lookbehind
(?<!        # look behind and assert that you cannot match
 &#         # an ampersand followed by a hash symbol
)           # end lookbehind
\w+         # match one or more word characters
;           # match a semicolon

替换为字符串'$0 '

如果这对你不起作用,请告诉我

当然,您也可以使用[a-zA-Z0-9]代替\w来避免匹配分号,但我认为这不会给您带来任何麻烦

此外,您可能还需要转义哈希符号(因为这是正则表达式注释符号),如下所示:

\b(?<!&)(?<!&\#)\w+;

编辑不确定,但我猜测将单词边界放在开头会使其更有效率(因此不太可能使您的服务器崩溃),所以我在表达式和分解中进行了更改。 ..

编辑 2 ...以及有关您的表达可能导致服务器崩溃的原因的更多信息:灾难性回溯——我认为这适用(?)嗯....不过是很好的信息

最终编辑如果您只想在分号后添加一个空格,如果它后面还没有空格(即在 的情况下添加一个pellentesque;odiopellentesque; odio在添加了额外的不必要的空格:

\b(?<!&)(?<!&\#)\w+;(?!\s)
于 2012-04-04T21:12:16.310 回答
0

对于这样的问题,回调可能会有所帮助。

(&(?:[A-Za-z_:][\w:.-]*|\#(?:[0-9]+|x[0-9a-fA-F]+)))?;

展开

(          # Capture buffer 1
   &                              # Ampersand '&'
   (?: [A-Za-z_:][\w:.-]*         # normal words
     | \#                         # OR, code '#'
       (?: [0-9]+                       # decimal
         | x[0-9a-fA-F]+                # OR, hex 'x'
       )
   )
)?         # End capture buffer 1, optional
;          # Semicolon ';'

测试用例http://ideone.com/xYrpg

<?php

$line = '
  Coca&#8209;Cola
  Beverage;Food;Music
';

$line = preg_replace_callback(
        '/(&(?:[A-Za-z_:][\w:.-]*|\#(?:[0-9]+|x[0-9a-fA-F]+)))?;/',
        create_function(
            '$matches',
            'if ($matches[1])
               return $matches[0];
             return $matches[0]." ";'
        ),
        $line
    );
echo $line;
?> 
于 2012-04-04T22:46:29.450 回答
0

您可以使用负面的回顾:

preg_replace('/(?<=[^\d]);([^\s])/', '; \1', $text)

因为我手头没有电脑,所以没有测试过,但是这个或它的轻微变化应该可以工作。

于 2012-04-04T20:56:30.633 回答