Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow regex match with one character wrong

Tags:

regex

php

I'm trying to figure out if there's an easy way to have a particular regex give matches that are correct except for one character. (Working in PHP if that matters).

For example, for the pattern 'apples', I want to find not only occurrences of "apples" but also "appxes", "opples", "applis", etc.

Is there any good way to accomplish this? Thanks in advance!

like image 352
G.S. Avatar asked Sep 14 '25 06:09

G.S.


2 Answers

Use levenshtein function instead of regex. Here are the docs.

On example echo levenshtein("abcd","abce") prints out: 1.

Edit: Please also note that this function will compare strings of different lengths, so additional check could be needed. See @Vulcan's comment below.

like image 107
kamituel Avatar answered Sep 15 '25 22:09

kamituel


Your regex string:

[A-z]pples|A[A-z]ples|Ap[A-z]les|Appl[A-z]es|Appl[A-z]s|Apple[A-z]
like image 34
rbedger Avatar answered Sep 15 '25 22:09

rbedger