PHP 搜索字符串(带通配符)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2305362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Php search string (with wildcards)
提问by Baehr
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").
有没有办法在字符串中放入通配符?我问的原因是因为目前我有一个函数来搜索两个子字符串之间的子字符串(即在句子“my dog has fleas”中抓取“my”和“has fleas”之间的内容,导致“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".
我想要做的是让它在字符串中使用通配符进行搜索。所以说我在“我的狗有跳蚤”这句话中在“%WILDCARD%”和“有跳蚤”之间搜索——它仍然会输出“狗”。
I don't know if I explained it too well but hopefully someone will understand me :P. Thank you very much for reading!
我不知道我是否解释得很好,但希望有人能理解我:P。非常感谢您的阅读!
回答by Luká? Lalinsky
This is one of the few cases where regular expressions are actually helpful. :)
这是正则表达式真正有用的少数情况之一。:)
if (preg_match('/my (\w+) has/', $str, $matches)) {
echo $matches[1];
}
See the documentation for preg_match.
请参阅preg_match的文档。
回答by user3026944
wildcard pattern could be converted to regex pattern like this
通配符模式可以像这样转换为正则表达式模式
function wildcard_match($pattern, $subject) {
$pattern = strtr($pattern, array(
'*' => '.*?', // 0 or more (lazy) - asterisk (*)
'?' => '.', // 1 character - question mark (?)
));
return preg_match("/$pattern/", $subject);
}
if string contents special characters, e.g. \.+*?^$|{}/'#, they should be \-escaped
如果字符串包含特殊字符,例如 \.+*?^$|{}/'#,它们应该被 \-escaped
don't tested:
不要测试:
function wildcard_match($pattern, $subject) {
// quotemeta function has most similar behavior,
// it escapes \.+*?^$[](), but doesn't escape |{}/'#
// we don't include * and ?
$special_chars = "\.+^$[]()|{}/'#";
$special_chars = str_split($special_chars);
$escape = array();
foreach ($special_chars as $char) $escape[$char] = "\$char";
$pattern = strtr($pattern, $escape);
$pattern = strtr($pattern, array(
'*' => '.*?', // 0 or more (lazy) - asterisk (*)
'?' => '.', // 1 character - question mark (?)
));
return preg_match("/$pattern/", $subject);
}
回答by anmont
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:
我同意正则表达式比通配符灵活得多,但有时您想要的只是一种定义模式的简单方法。对于寻找便携式解决方案(不仅仅是 *NIX)的人来说,这是我对该功能的实现:
function wild_compare($wild, $string) {
$wild_i = 0;
$string_i = 0;
$wild_len = strlen($wild);
$string_len = strlen($string);
while ($string_i < $string_len && $wild[$wild_i] != '*') {
if (($wild[$wild_i] != $string[$string_i]) && ($wild[$wild_i] != '?')) {
return 0;
}
$wild_i++;
$string_i++;
}
$mp = 0;
$cp = 0;
while ($string_i < $string_len) {
if ($wild[$wild_i] == '*') {
if (++$wild_i == $wild_len) {
return 1;
}
$mp = $wild_i;
$cp = $string_i + 1;
}
else
if (($wild[$wild_i] == $string[$string_i]) || ($wild[$wild_i] == '?')) {
$wild_i++;
$string_i++;
}
else {
$wild_i = $mp;
$string_i = $cp++;
}
}
while ($wild[$wild_i] == '*') {
$wild_i++;
}
return $wild_i == $wild_len ? 1 : 0;
}
Naturally the PHP implementation is slower than fnmatch(), but it would work on any platform.
PHP 实现自然比 fnmatch() 慢,但它可以在任何平台上工作。
It can be used like this:
它可以像这样使用:
if (wild_compare('regex are * useful', 'regex are always useful') == 1) {
echo "I'm glad we agree on this";
}
回答by kennytm
Use a regex.
使用正则表达式。
$string = "My dog has fleas";
if (preg_match("/\S+ (\S+) has fleas/", $string, $matches))
echo ($matches[1]);
else
echo ("Not found");
\Smeans 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 $matchesarray.
\S表示任何非空格字符,+表示前面的\S+一个或多个,因此表示匹配一个或多个非空格字符。(…)表示捕获子匹配的内容并放入$matches数组。

