Search code examples
phpregexpreg-match

Getting matches in preg_match not working


I've been trying to understand how to get preg_match to work with the following pattern:

\[flexvideo.* id="(?<id>[^"']+)" type="(?<type>[^"']+)".*\]\iU

Effectively, I have the following code: [flexvideo id="" type="" aspect=""]

which can also be written as: [flexvideo id='' type='' aspect='']

Attributes can be in any order.

What I don't understand is when I use the ' instead of the " I get no results that match, where the other doesn't.

Additionally, I'd like the matches to show empty fields if there is no match.

Here is what I've been working with: http://www.phpliveregex.com/p/dGA


Solution

  • Use

    • ["\'] => " or '
    • [^"\']* => any char excepts " and ' 0 or more times

    Code:

    $str = '[flexvideo id="" type=\'biuahsdiuasd\' aspect="c"]\iU';
    $reg = '/\[flexvideo\s+id=["\'](?<id>[^"\']*)["\']\s+type=["\'](?<type>[^"\']*).*?\]/';
    preg_match($reg, $str, $match);
    print_r($match);
    

    Output:

    Array
    (
        [0] => [flexvideo id="" type='biuahsdiuasd' aspect="c"]
        [id] => 
        [1] => 
        [type] => biuahsdiuasd
        [2] => biuahsdiuasd
    )