4

In PHP there is the levenshtein-method, right?

With it you can check how similar two strings are.

But is there a way that you have a pattern (regEx) that you compare with a string?

So let's say you have the pattern: L234X567PP All of the Numbers are changeable. Just the letters must be there (and at exactly the same position)

So now you have some Strings: L000X000PP L987X123PP Those should be valid.

B000X678XX This is not valid but levenshtein detects a similarity and could ask to correct the wrong letters (is that possible?)

How can you do this with PHP?

3 Answers 3

2

An interesting concept, but why not try this?

if( preg_match("/^L\d{3}X\d{3}PP$/",$input)) { /* all ok! */ }
elseif( preg_match("/^[A-Z]\d{3}[A-Z]\d{3}[A-Z][A-Z]$/i",$input)) { /* letters were wrong */ }
// ... continue defining possible errors manually
Sign up to request clarification or add additional context in comments.

1 Comment

That is a nice idea. I will try that out. And thanks to the others as well.
2

Yes, you can do this using PHP. Here is the regex you would use for your specified pattern:

$regex = '/^L[0-9]{3}X[0-9]{3}PP$/';
$input = 'L000X000PP';
if (preg_match($regex, $input) == 1) {
    echo "Matches!";
} else {
    echo "Does Not Match!"
}

1 Comment

How does this answer the question of "almost matching"?
1

That is where soundex function steps in. See this code snippet:

$str1 = "L000X000PP";
$str2 = "L987X123PP";
$_str1 = soundex ($str1);
$_str2 = soundex ($str2);

var_dump($_str1);
var_dump($_str2);
var_dump($_str1 == $_str2);

OUTPUT:

string(4) "L210"
string(4) "L210"
bool(true)

2 Comments

thank you. I will try that out. But I think function could be problematic at some point because of the pronunciation. But I will try it, maybe it helps :)
This may turn out to be pretty useful for you as even L987654321X1234578PP produces same L210 output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.