简体   繁体   中英

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</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 " .

函数htmlentities()将"转换为&quot;尝试:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM