Search code examples
phpregexattributesplaceholdertext-parsing

Parse a square braced placeholder and get the value of a specific attribute


Some links like these:

[links url='http://www.google.com.hk' title='Google' image='']google[/links]
[links url='http://hk.yahoo.com' title='yahoo' image='']yahoo[/links]

How to use PHP Regular expression get the url attributes?

http://www.google.com.hk
http://hk.yahoo.com

Solution

  • This should get you started:

    preg_match_all("/\[links[^\]]+url='([^']+)'/", '{{your data}}', $arr, PREG_PATTERN_ORDER);
    

    Explanation of the regex:

    /
    \[                  //An excaped "[" to make it literal.
    links               //The work "links"   
    [^\]]+              //1+ non-closing brackent chars ([^] is a negative character class)
    url='               //The work url='
    ([^']+)             //The contents inside the '' in a caputuring group
    /