[英]Regular expression to ignore space and special characters in a group of words [php]
I'm looking for a regex to match all of these alternative strings in a text, for example : 我正在寻找一个正则表达式来匹配文本中所有这些替代字符串,例如:
Mist X & Rock-n-Roll 迷雾X和摇滚
MistX & RocknRoll MistX和RocknRoll
Mist-X and Rock n Roll Mist-X和Rock n Roll
Mist X Rock n Roll 雾X摇滚乐
MistX-RocknRoll MistX-RocknRoll
mist X - rock n roll 薄雾X-摇滚乐
etc... 等等...
I want to ignore spaces / special characters / cases, and get the name of the music band. 我想忽略空格/特殊字符/大小写,并获取乐队的名称。 I'm very bad at regular expression, and all I have now is : 我对正则表达式非常不好,现在我拥有的只是:
$string = "Mist X & Rock-n-Roll";
$valid = preg_match("/\b".$string."\b/i", $text);
It match only if it's exactly the same. 仅在完全相同时才匹配。
My final idea was to delete all the spaces / special chars inside the $text and the $string, to match with this next regex, but It could return a no expected result. 我的最终想法是删除$ text和$ string中的所有空格/特殊字符,以与下一个正则表达式匹配,但是它可能会返回预期的结果。 (like this example above) (如上面的示例)
$string = "Son-B";
$new_string = strtolower(str_replace('-', '', $string));
$text = "I like my son because he is smart";
$new_text = strtolower(str_replace(' ', '', $text));
preg_match("/".$new_string."/i", $new_text); // => true while I don't want to match !
Any idea ? 任何想法 ? Thanks a lot. 非常感谢。
mist(\W)?x.*rock(\W)?n(\W)?roll
Matched all examples given. 匹配给出的所有示例。
Edit: to ensure it's not part of another word, add \\b
to both ends. 编辑:为确保它不是另一个单词的一部分,请在两端添加\\b
。
try this to start to compare easily : 试试这个,开始比较容易:
$list = array(
"Mist X & Rock-n-Roll",
"MistX & RocknRoll",
"Mist-X and Rock n Roll",
"Mist X Rock n Roll",
"MistX-RocknRoll",
"mist X - rock n roll",
);
foreach ($list as $e) {
$e = strtolower($e);
echo preg_replace("![^a-z]!", "", $e);
echo "<br/>";
}
result : 结果:
mistxrocknroll 薄雾摇滚
mistxrocknroll 薄雾摇滚
mistxandrocknroll 薄雾摇滚乐
mistxrocknroll 薄雾摇滚
mistxrocknroll 薄雾摇滚
mistxrocknroll 薄雾摇滚
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.