Preg_match 当字符串有时是单个单词时?

发布于 2024-11-15 04:11:47 字数 190 浏览 2 评论 0原文

我正在尝试从电子邮件主题行中提取一个单词,用作附加电子邮件的类别。只要 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

油饼 2024-11-22 04:11:47

假设 \b(?:word1|word2|word3)\b

它与“word1”不匹配的原因是因为您包含了单词分隔符 \b

你能做的就是总是注入单词分隔符:

preg_match("\b(?:word1|word2|word3)\b", "." . $subject . ".", $matches);

粗鲁但有效。

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:

preg_match("\b(?:word1|word2|word3)\b", "." . $subject . ".", $matches);

Crude but effective.

妄断弥空 2024-11-22 04:11:47

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文