PHP搜索字符串(带通配符) [英] Php search string (with wildcards)

查看:58
本文介绍了PHP搜索字符串(带通配符)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将通配符放在字符串中?我问的原因是因为当前我有一个功能可以搜索两个子字符串之间的子字符串(即在我的狗有跳蚤"句子中抓取"my"和"has fleas"之间的内容,导致"dog" ).

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); 
} 

我想做的是在字符串中使用通配符进行搜索.所以说我在句子我的狗有跳蚤"中的%WILDCARD%"和有跳蚤"之间搜索-它仍然会输出"dog".

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".

我不知道我是否解释得太好,但希望有人会理解我的:P.非常感谢您的阅读!

I don't know if I explained it too well but hopefully someone will understand me :P. Thank you very much for reading!

推荐答案

这是正则表达式实际上有用的少数情况之一. :)

This is one of the few cases where regular expressions are actually helpful. :)

if (preg_match('/my (\w+) has/', $str, $matches)) {
    echo $matches[1];
}

请参阅 preg_match 的文档.

这篇关于PHP搜索字符串(带通配符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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