Whity Nox
Whity Nox

Reputation: 3

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
MistX & RocknRoll
Mist-X and Rock n Roll
Mist X Rock n Roll
MistX-RocknRoll
mist X - rock n roll
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. (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.

Upvotes: 0

Views: 634

Answers (2)

Jessica
Jessica

Reputation: 7005

mist(\W)?x.*rock(\W)?n(\W)?roll

Regular expression visualization

Debuggex Demo

Matched all examples given.

Edit: to ensure it's not part of another word, add \b to both ends.

Upvotes: 2

mmm
mmm

Reputation: 1149

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

Upvotes: -1

Related Questions