I would like to match (with regex) two strings ignoring the fact that one string may or may not have hyphens and/or single-quote chars (in fact just ignore all punctuation in both strings).
The problem is both strings are within PHP variables, not literals which i can do easily however, but not with variables - any ideas please ... is this even possible.
For example like a pattern modifier /i which specifies case-insensitive comparisons - is there a modifier to say ignore punctuation just compare alpha-numeric strings ??
if (preg_replace("/['\-]/", '', $str1) == preg_replace("/['\-]/", '', $str2) {
...equal...
}
basically: strip out '
and -
from both strings, then compare the resulting stripped strings. If yout want case-insensitive, then do strtolower(preg_replace(....))
instead.
I am replacing all the non-alphanumeric + Space(\s
) characters from the both strings. Then using one string inside the regex to match against other one.
$str1 = "alexander. was a hero!!";
$str2 = "alexander, was a hero?";
if(preg_match(
"/^".preg_replace("/[^a-zA-Z0-9\s]/", "", $str1)."$/i",
preg_replace("/[^a-zA-Z0-9\s]/", "", $str2)
)){
print "matched!";
}
If you want, you may ignore the space(\s
) from the above regex.