PHP 搜索字符串(带通配符)
有没有办法在字符串中添加通配符?我之所以问这个问题,是因为目前我有一个函数可以搜索两个子字符串之间的子字符串(即抓取“我的狗有跳蚤”这句话中“我的”和“有跳蚤”之间的内容,从而得到“狗” )。
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
我想做的是让它在字符串中使用通配符进行搜索。假设我在“我的狗有跳蚤”这句话中在“%WILDCARD%”和“有跳蚤”之间搜索 - 它仍然会输出“狗”。
我不知道我是否解释得太好,但希望有人能理解我:P。非常感谢您的阅读!
Is there a way to put a wildcard in a string? The reason why I am asking is because currently I have a function to search for a substring between two substrings (i.e grab the contents between "my" and "has fleas" in the sentence "my dog has fleas", resulting in "dog").
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
What I want to do is have it search with a wildcard in the string. So say I search between "%WILDCARD%" and "has fleas" in the sentence "My dog has fleas" - it would still output "dog".
I don't know if I explained it too well but hopefully someone will understand me :P. Thank you very much for reading!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是正则表达式真正有用的少数情况之一。 :)
请参阅 preg_match 的文档。
This is one of the few cases where regular expressions are actually helpful. :)
See the documentation for preg_match.
通配符模式可以转换为正则表达式模式,如下所示
如果字符串包含特殊字符,例如 \.+*?^$|{}/'#,则
,它们应该是 \-转义的,不进行测试:
wildcard pattern could be converted to regex pattern like this
if string contents special characters, e.g. \.+*?^$|{}/'#, they should be \-escaped
don't tested:
使用正则表达式。
\S
表示任何非空格字符,+
表示前面的一个或多个字符,因此\S+
表示匹配一个或多个非空格字符。(…)
表示捕获子匹配的内容并放入$matches
数组中。Use a regex.
\S
means any non-space character,+
means one or more of the previous thing, so\S+
means match one or more non-space characters.(…)
means capture the content of the submatch and put into the$matches
array.我同意正则表达式比通配符灵活得多,但有时您想要的只是一种定义模式的简单方法。对于寻找便携式解决方案(不仅仅是 *NIX)的人来说,这是我的函数实现:
当然,PHP 实现比 fnmatch() 慢,但它可以在任何平台上工作。
它可以这样使用:
I agree that regex are much more flexible than wildcards, but sometimes all you want is a simple way to define patterns. For people looking for a portable solution (not *NIX only) here is my implementation of the function:
Naturally the PHP implementation is slower than fnmatch(), but it would work on any platform.
It can be used like this:
如果您坚持使用通配符(是的,PREG 更好),您可以使用该函数
fnmatch。
前任:
If you insist to use a wildcard (and yes, PREG is much better) you can use the function
fnmatch.
ex: