Shaun
Shaun

Reputation: 2181

Is it possible to compare two strings while ignoring one of the characters php?

If you have

$str1 = "h*llo";
$str2 = "hello";

is it possible to quickly compare them without first having to remove the * from str1, and the matching indexed character from str2?

The solution would need to work regardless of how many * are in the string, eg:

$str1 = "h*l*o";
$str2 = "hello";

Thanks for taking a look.

Upvotes: 0

Views: 1000

Answers (2)

John V.
John V.

Reputation: 4670

Yes, with regex, and more specifically preg_match for PHP. What you are looking for are "wildcards".

This is untested but should work for you:

$str1 = "h*llo";
$str2 = "hello";

//periods are a wildcards in regex
if(preg_match("/" . preg_quote(str_replace("*", ".*", $str1), "/") . "/", $str2)){
    echo "Match!";
} else {
    echo "No match";
}

EDIT: This should work for your case:

$str1 = "M<ter";
$str2 = "Moter";

//periods are a wildcards in regex
if(preg_match("/" . str_replace("\<", ".*", preg_quote($str1, "/")) . "/", $str2)){
    echo "Match!";
} else {
    echo "No match";
}

Upvotes: 3

CIRCLE
CIRCLE

Reputation: 4869

You can use similar_text() to compare two strings and accept if the result is above e.g. 80%.

 similar_text($str1, $str2, $percent); 

Example:

$str1 = 'AAA';
$str1 = '99999';

similar_text($str1, $str2, $percent); 
echo $percent; // e.g. 0.000

$str1 = "h*llo";
$str2 = "hello";

similar_text($str1, $str2, $percent); 
echo $percent; // e.g. 95.000

See more here PHP SIMILAR TEXT

Upvotes: 1

Related Questions