Regex / Preg: No match, if found

一个人想着一个人 提交于 2019-12-20 06:21:37

问题


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:


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)


来源:https://stackoverflow.com/questions/12447818/regex-preg-no-match-if-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!