0

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 ??

2 Answers 2

1
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.

1
  • Thanks works like a dream - Just needed to add closing parenthesis in 'if' block ... and used chr(32) to represent spaces as i dont like using literal white-space in coding - thanks
    – Flim Flam
    Commented Mar 10, 2014 at 18:05
0

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.

1
  • yes thanks - just as @Marc B solution but not as concise - i too thought of something similar but doesn't the negation ^ add extra expense. I think an explicit exclusion list as used inMarc B solution is less intensive.
    – Flim Flam
    Commented Mar 10, 2014 at 18:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.