Search code examples
phpregexstringpreg-match

How yo create a pattern for string match and how to get other arguments from the string


I don't know how to create a regular expression. I wanted to get subtrings from a string. In my case the string is [_formatdate_form_date "D, d M y"]. I wanted the field name form_date and the string between the double quotes i.e. D, d M y. I searched for the PHP functions like preg_match but all requires a pattern. So how to create a pattern for this


Solution

  • You can do something like that :

    $str = '[_formatdate_form_date "D, d M y"]';
    $regex = "/_formatdate_(.*)\s\"(.*)\"/";
    
    preg_match_all($regex, $str, $matches);
    var_dump($matches);
    

    And the result $matches :

    enter image description here

    So to acces you have to do : $matches[1][0] or $matches[2][0]

    But to understand what does it make, I suggest you to learn a minimum about regular expression : Learn Regular Expression