Php 获取两个字符串之间的差异

Php 获取两个字符串之间的差异,php,wildcard,Php,Wildcard,我正在创建一个通配符搜索/替换函数,需要找到两个字符串之间的差异。我尝试了一些功能,如array_diff和preg_match,浏览了10个谷歌页面,但没有找到解决方案 我现在有一个简单的解决方案,但希望在通配符之前实现对未知值的支持 以下是我得到的: function wildcard_search($string, $wildcard) { $wildcards = array(); $regex = "/( |_|-|\/|-|\.|,)/"; $split_st

我正在创建一个通配符搜索/替换函数,需要找到两个字符串之间的差异。我尝试了一些功能,如
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)

这样做是否可以避免数百个循环等带来的麻烦?

我会将您的函数更改为使用转义的
\*
字符,并将其替换为
(.*)

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)