Preg_match 当字符串有时是单个单词时?
我正在尝试从电子邮件主题行中提取一个单词,用作附加电子邮件的类别。只要 Preg_match 不只是一个单词(这就是我想做的),它就可以很好地工作。如果主题行中只有一个单词,我只会得到一个空数组。在这种情况下,我尝试将 $matches 视为变量,但这也不起作用。谁能告诉我 preg_match 是否适用于单个单词,或者更好的方法是什么?
非常感谢
I'm trying to pull a word out of an email subject line to use as a category for attached email. Preg_match works great as long as it's not just a single word (which is what I'd like to do anyway). If there is only one word in the subject line, I just get an empty array. I've tried to treat $matches as just a variable in that case, but that doesn't work either. Can anyone tell me if preg_match will work on a single word, or what the better way to do this would be?
Thanks very much
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设
\b(?:word1|word2|word3)\b
它与“word1”不匹配的原因是因为您包含了单词分隔符
\b
。你能做的就是总是注入单词分隔符:
粗鲁但有效。
Assuming
\b(?:word1|word2|word3)\b
The reason it wont match "word1" is because you included a word separator, the
\b
.What you can do is just simply always inject the word separator:
Crude but effective.
preg_match
将适用于一个字符长的字符串。我认为这里的问题可能是你的正则表达式。我的猜测是,您正在测试空格,因为它没有找到任何空格,所以它说没有匹配项。尝试将'^([^\s]*)$|'
附加到您的正则表达式中,我打赌它会开始拾取这些单词值。 ([^\s]
表示给我任何其中没有空格的内容,|
表示“或”。通过将其添加到正则表达式的前面,它将包括没有空格的东西或任何你已经拥有的东西)preg_match
will work on a string one character long. I think that the issue here is probably your regex. My guess is that you're testing for whitespace and because it isn't finding any it says that there is no match. Try appending'^([^\s]*)$|'
to your regex and I wager it will start picking up those one word values. ([^\s]
means give me anything which has no spaces in it,|
means 'or'. By adding it to the front of your regex, it will include things without whitespace or whatever you already had)