php - 比较两个字符串是否具有相似性
问题描述
我正在寻找 PHP 中的一个函数,它可以将两个字符串与数字进行比较。他们应该至少有 5 个相同的字母/数字以连续的顺序排列。
示例:
AD-2018-34567-234
并且cd 34567
两者都包含相同的字母/数字=34567
或者
10256
两者cd 10256
都包含10256
或者
1234567890- rfwet043-123455-cd1234-sdf
两者4edgs-cd12340e-3ed
都包含cd1234
在这里尝试使用此功能,但不符合我的需求。
$str1 = "AD-2018-34567-234";
$str2 = "cd 34567";
$str3 = "10256";
$str4 = "cd 10256";
$str5= "1234567890-rfwet043-123455-cd1234-sdf";
$str6= "4edgs-cd12340e-3ed";
if(strpos($str1, $str2) !== false) {
echo "matched";
}else{
echo "not matched";
}
if(strpos($str3, $str4) !== false) {
echo "matched";
}else{
echo "not matched";
}
if(strpos($str5, $str6) !== false) {
echo "matched";
}else{
echo "not matched";
}
也试过strpos
了,都不配。
解决方案
这通过循环查找字符串并且一次只使用五个字符来匹配你想要的。
$str1 = ["AD-2018-34567-234","10256","1234567890-rfwet043-123455-cd1234-sdf"];
$str2 = ["cd 34567","cd 10256","4edgs-cd12340e-3ed"];
foreach($str1 as $key => $str){
$find = $str2[$key];
$l = strlen($find);
$match = false;
for($i=0; $i<=($l-5);$i++){ // loop the find string
//echo $str . " " . substr($find,$i, 5) . "\n"; // debug
if(strpos($str, substr($find,$i, 5)) !== false) { // take five characters at the time and stros them
$match = true;
break;
}
}
if($match){
echo "match\n";
}else{
echo "no match\n";
}
}
如果您取消注释被注释的行,您将看到它是如何工作的
$str1 = "AD-2018-34567-234";
$find = "cd 34567";
$l = strlen($find);
$match = false;
for($i=0; $i<=($l-5);$i++){ // loop the find string
//echo $str1 . " " . substr($find,$i, 5) . "\n"; // debug
if(strpos($str1, substr($find,$i, 5)) !== false) { // take five characters at the time and stros them
$match = true;
break;
}
}
if($match){
echo "match\n";
}else{
echo "no match\n";
}
推荐阅读
- python - How to apply condition in PySpark to keep null only if one else remove nulls
- node.js - 将标头提供给 API 时的 Access-Control-Allow-Origin
- idris - 以数据类型编码二叉搜索树
- python - 为什么 Python 只能读取“下载”文件夹中的 CSV 而不能读取我 PC 上的其他文件夹中的 CSV?
- recursion - 递归是解决树问题的唯一方法吗
- ios - 故事板中的条形按钮未显示
- makefile - 如何将不同目录中的源代码编译成一个目录(Makefile)中的目标文件?
- amazon-web-services - 为 lambda 标记无服务器日志组
- java - 如果失败,请重试 Firestore
- c# - 使用 VB.Net / C# 读取 JSON