问题
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