Reputation: 1105
I am looking for a function in PHP that can do a comparison of two strings with numbers. They should at least 5 same letters/number in consecutive order.
Example:
AD-2018-34567-234
and cd 34567
both contains same letters/number = 34567
OR
10256
and cd 10256
both contains 10256
OR
1234567890- rfwet043-123455-cd1234-sdf
and 4edgs-cd12340e-3ed
both contains cd1234
Tried using this function here but doesn't meet my needs.
$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";
}
Tried also strpos
all did not match.
Upvotes: 1
Views: 177
Reputation: 23958
This does what you want by looping the find string and only using five charaters at the time to match with.
$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";
}
}
If you uncomment the line that is commented you will see how it works
$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";
}
Upvotes: 1
Reputation: 12403
tryout this solution
<?php
$str1 = "AD-2018-34567-234";
$str2 = "cd 34567";
$str3 = "10256";
$str4 = "cd 10256";
$str5= "1234567890-rfwet043-123455-cd1234-sdf";
$str6= "4edgs-cd12340e-3ed";
$val=similar_text($str1, $str2,$per);
if($val>=5){
echo "Matched";
}else{
echo "Not matched";
}
$val=similar_text($str3, $str4,$per);
if($val>=5){
echo "Matched";
}else{
echo "Not matched";
}
$val=similar_text($str5, $str6,$per);
if($val>=5){
echo "Matched";
}else{
echo "Not matched";
}
Upvotes: 0