简体   繁体   English

我如何使用正则表达式比较php字符串变量

[英]how do i compare php string vars using regex

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. 问题是两个字符串都在PHP变量中,而不是我可以轻松实现的文字,但是不包含变量-请提出任何想法...甚至可能。

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 ?? 例如,像模式修饰符/ i指定不区分大小写的比较-是否有修饰符说忽略标点,只比较字母数字字符串?

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. 如果您不区分大小写,请改用strtolower(preg_replace(....))

I am replacing all the non-alphanumeric + Space( \\s ) characters from the both strings. 我要替换两个字符串中的所有非字母数字+空格( \\s )字符。 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. 如果需要,可以忽略上述正则表达式中的空格( \\s )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM