开发者

Why this regex doesn't exclude this word?

I have this code :

$str=preg_replace(
    '#\b[^"](Hello User)#',         
    '<a href="$1">$1</a>',
    $str);
return nl2br($str);

So, I'd like to replace every occurences of Hello User that doesnt start with ".

For example with string :

Hello User\n
"Hello User\n
Hello User\n
"Hello User"\n

I'll aspect this result :

<a href="Hello User">Hello User</a><br />
"Hello User<br />
<a href="Hello User">Hello User</a><br />
"Hello User"<br />

But in fact the output is the opposite :

Hello User<br />
"<a href="Hello User">Hello User开发者_StackOverflow</a><br />
Hello User<br />
"<a href="Hello User">Hello User</a>"<br />

Why? And how can I fix this trouble?

EDIT

You can see an example here http://codepad.org/2Q466lx2


The reason is that [^"] expects to match a character (anything but a "). Since your first Hello User is at the start of the string, it fails.

Use a negative lookbehind assertion instead:

$str=preg_replace(
    '#(?<!")(Hello User)#',           
    '<a href="$1">$1</a>',
    $str);

This matches Hello User only if it is not preceded by a ".


Function htmlentities() convert " to &quot; try:

#(?<!&quot;)(Hello User)#
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜