0

我有这段文字:

$string = '
And God<WH430> said<WH559>, Behold<WH2009>, I have given<WH5414> you every herb<WH6212>
bearing<WH2232> seed<WH2233>, which <FI>is<Fi> upon the face<WH6440> of all the 
earth<WH776>, and every tree<WH6086>, in the which <FI>is<Fi> the fruit<WH6529> of a 
tree<WH6086> yielding<WH2232> seed<WH2233>; to you it shall be<WH1961> for meat<WH402>.
<RF>bearing...: Heb. seeding seed<Rf><RF>yielding...: Heb. seeding seed<Rf>';

而这段代码:

$search = '/<RF>(.*)<Rf>/';
$replace = '&nbsp;<sup data-tooltip class="has-tip" title="$1"> note </sup>';
$string = preg_replace($search, $replace, $string);

我希望正则表达式单独替换每个标签,但是使用此代码我得到了:

And God<WH430> said<WH559>, Behold<WH2009>, I have given<WH5414> you every herb<WH6212>
bearing<WH2232> seed<WH2233>, which <FI>is<Fi> upon the face<WH6440> of all the 
earth<WH776>, and every tree<WH6086>, in the which <FI>is<Fi> the fruit<WH6529> of a 
tree<WH6086> yielding<WH2232> seed<WH2233>; to you it shall be<WH1961> for meat<WH402>.
<sup data-tooltip class="has-tip" title="bearing...: Heb. seeding seed<Rf>
<RF>yielding...: Heb. seeding seed"> note </sup>

所以,它只是跳过了中间的标签,一直持续到文本末尾的最后一个标签……我怎样才能让……一些 tekst……的每个实例都被单独替换?

4

2 回答 2

0

您的正则表达式太贪婪,因此.*消耗尽可能多的文本。将其修改为:

/<RF>(.*?)<Rf>/
        ^
        Added question mark

这将导致正则表达式捕获尽可能少的文本以匹配表达式。

于 2013-10-25T20:20:33.037 回答
0

如果您确定您的文本不包含<,您可以这样做:

$search = '~<RF>([^<]*+)<Rf>~';

否则你可以使用:

$search = '~<RF>((?>[^<]++|<(?!Rf>))*+)<Rf>~';
于 2013-10-25T20:34:03.647 回答