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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

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.

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.