Regex / Preg: No match, if found

2020-05-02 03:58发布

I'm trying to do some PHP preg. But it seems to i can't get it to match if i want a string without something in it.

Example:

Hello! My name is [b]Peter Jack[/b]

If Peter Jack is found with his last name, it will NOT match, but if its found "[b]Peter[/b]" it will match.

Anyone who I'm kinda bad at explaining things, comment if there is anything else you need to help me solve this.


Another way I can say it about, is, if i got a link to a website, it will match and do the stuff in the preg_replace, but if the link to the website ends with like .png (an image) it will not match and will not make a link.

example.com/image.png

Will not be matched because it contains .png

example.com/image

Will be matched because it does not contain .png

1条回答
劫难
2楼-- · 2020-05-02 04:21

It's unclear what you want to find. If it's just [b]Peter[/b], then you don't need a regex.

If you want to find a single "word" surrounded by BBCode bold tags, use

preg_match('%\[b\]\w*\[/b\]%', $subject)

If you want to find anything within BBCode bold tags as long as it doesn't contain Jack, use

preg_match(
    '%\[b\]     # Match [b]
    (?:         # Try to match...
     (?!Jack)   # (unless the word "Jack" occurs there)
     .          # any character
    )*?         # any number of times, as few as possible
    \[/b\]      # Match [/b]%x', 
    $subject)
查看更多
登录 后发表回答