Regex/Preg:不匹配,如果找到 [英] Regex / Preg: No match, if found

查看:46
本文介绍了Regex/Preg:不匹配,如果找到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一些 PHP preg.但是如果我想要一个没有东西的字符串,我似乎无法让它匹配.

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.

示例:

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

如果找到 Peter Jack 的姓氏,则不会匹配,但如果找到[b]Peter[/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.

我可以说的另一种方式是,如果我得到一个网站链接,它将匹配并执行 preg_replace 中的内容,但如果该网站的链接以 .png(图像)结尾不会匹配,也不会建立链接.

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

不会匹配,因为它包含 .png

Will not be matched because it contains .png

example.com/image

将被匹配,因为它包含 .png

Will be matched because it does not contain .png

推荐答案

不清楚您要查找什么.如果只是[b]Peter[/b],那么你就不需要正则表达式.

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

如果你想找到一个被 BBCode 粗体标签包围的单词",使用

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

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

如果您想在 BBCode 粗体标签中查找任何内容,只要它不包含 Jack,请使用

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)

这篇关于Regex/Preg:不匹配,如果找到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆