我正在创建一个通配符搜索/替换函数,需要找到两个字符串之间的区别。我尝试了一些功能,例如array_diff
和preg_match
,浏览了大约10个谷歌页面,没有解决方案。
我现在有一个简单的解决方案,但是希望在通配符之前实现对未知值的支持
这是我得到的:
function wildcard_search($string, $wildcard) {
$wildcards = array();
$regex = "/( |_|-|\/|-|\.|,)/";
$split_string = preg_split($regex, $string);
$split_wildcard = preg_split($regex, $wildcard);
foreach($split_wildcard as $key => $value) {
if(isset($split_string[$key]) && $split_string[$key] != $value) {
$wildcards[] = $split_string[$key];
}
}
return $wildcards;
}
使用示例:
$str1 = "I prefer Microsoft products to Apple but love Linux"; //original string
$str2 = "I prefer * products to * but love *"; //wildcard search
$value = wildcard_search($str1, $str2);
//$value should now be array([0] => "Microsoft", [1] => "Apple", [2] => "Linux");
shuffle($value);
vprintf('I prefer %s products to %s but love %s', $value);
// now we can get all kinds of outputs like:
// I prefer Microsoft products to Linux but love Apple
// I prefer Apple products to Microsoft but love Linux
// I prefer Linux products to Apple but love Microsoft
// etc..
我想在通配符之前实现对未知值的支持。
示例:
$value = wildcard_search('Stackoverflow is an awesome site', 'Stack* is an awesome site');
// $value should now be array([0] => 'overflow');
// Because the wildcard (*) represents overflow in the second string
// (We already know some parts of the string but want to find the rest)
这可以在没有麻烦的情况下完成数百个循环等吗?
答案 0 :(得分:6)
我将您的功能更改为使用preg_quote
,并将转义的\*
字符替换为(.*?)
代替:
function wildcard_search($string, $wildcard, $caseSensitive = false) {
$regex = '/^' . str_replace('\*', '(.*?)', preg_quote($wildcard)) . '$/' . (!$caseSensitive ? 'i' : '');
if (preg_match($regex, $string, $matches)) {
return array_slice($matches, 1); //Cut away the full string (position 0)
}
return false; //We didn't find anything
}
示例强>:
<?php
$str1 = "I prefer Microsoft products to Apple but love Linux"; //original string
$str2 = "I prefer * products to * but love *"; //wildcard search
var_dump( wildcard_search($str1, $str2) );
$str1 = 'Stackoverflow is an awesome site';
$str2 = 'Stack* is an awesome site';
var_dump( wildcard_search($str1, $str2) );
$str1 = 'Foo';
$str2 = 'bar';
var_dump( wildcard_search($str1, $str2) );
?>
<强>输出强>:
array(3) {
[0]=>
string(9) "Microsoft"
[1]=>
string(5) "Apple"
[2]=>
string(5) "Linux"
}
array(1) {
[0]=>
string(8) "overflow"
}
bool(false)