Search code examples
phpregexpreg-replacepreg-match

Match string with another string having dynamic string content


I want to match a 1st string with a 2nd string. The second string will have dynamic content inside {}. It is also separated by | since I need to match the 1st string with 2nd string's multiple values and return boolean. Also, I need the dynamic variables from 1st string if the 1st string value matches with 2nd string's partial value. I have tried and searched a lot and came up to this

$message = "wala hi";
$pattern = "Mujhey|mujhe|mujh'y|mjy?|mujy|wala {dynamicontent}";
$pattern = str_replace('/', '\/', $pattern);
$text = '/^'.preg_replace('/\{((?:(?!\d+,?\d+?)\w)+?)\}/', '(?<$1>.*)', $pattern).' ?$/miu';
$regexMatched = (bool) preg_match($text, $message, $matches) || (bool) preg_match($text, '', $matches);
var_dump([$regexMatched, $matches]);

It's still not working properly.

following can be the inputs, pattern to match = and the desired outputs:

  1. input: play demo-song, pattern: play {song}, output: returns true and demo-song
  2. input: pley demo-song, pattern: play {song}, output: returns false and null
  3. input: show hoizer profile, pattern: show {artist} profile, output: returns true and hoizer
  4. input: show 2019 season of GOT, pattern: show {year} season of {series}, output: returns true and [0=>2019, 1=>GOT]

PS: The strings will contain emojis and ?,' as well.


Solution

  • So far this is the solution which fulfills my requirement. Thank you for your help @Emma.

    function checkPattern($stringToTest, $pattern) {
        str_replace("\|", "|", preg_quote($pattern));
        $pattern = str_replace("|", "$|^", preg_replace('/' . preg_quote('{') . '.*?' .preg_quote('}') . '/', '(.*)', $pattern));
        $regexMatched = (bool) preg_match("/^".$pattern."$/mi", $stringToTest, $matches);
        var_dump([$regexMatched, end($matches)]);
    }
    
    //test 1 returns [true, hozier]
    $stringToTest = "play songs by hozier";
    $pattern = "play songs by {artist}|play {artist} songs|{artist} songs"; 
    checkPattern($stringToTest, $pattern);
    
    //test 2 returns [false, false]
    $stringToTest = "show hozier";
    $pattern = "show {artist} profile|view {artist} profile"; 
    checkPattern($stringToTest, $pattern);