gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:32:44 26 4
gpt4 key购买 nike

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

是否可以通过 数百个循环 等轻松完成?

最佳答案

我会更改您的函数以使用 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)

DEMO

关于php - 获取两个字符串之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21029314/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com