phptext-parsing

Parse a string containing square braced tags followed by their label into an array


I've built the following code and it's doing what I need for the array portion of my code.

$demo = '[url=https://www78.zippyshare.com/v/AQg3SYMQ/file.html]1. Like Im Fabo.mp3[/url][url=https://www78.zippyshare.com/v/TPRugyFb/file.html]2. Stic _Em Up.mp3';
$arr = explode("[/url]", $demo);
print '<pre>';
print_r($arr);
print '</pre>';

The above portion returns this.

Array
(
    [0] => [url=https://www78.zippyshare.com/v/AQg3SYMQ/file.html]1. Like Im Fabo.mp3
    [1] => [url=https://www78.zippyshare.com/v/TPRugyFb/file.html]2. Stic _Em Up.mp3
)

I am wondering now how I can explode each portion of the above to return something like this.

Array
(
    [0] => https://www78.zippyshare.com/v/AQg3SYMQ/file.html
    [0] => 1. Like Im Fabo.mp3
    [1] => https://www78.zippyshare.com/v/TPRugyFb/file.html
    [1] => 2. Stic _Em Up.mp3
)

So that I am able to acquire the file path, and the file name with ease.


Solution

  • You can use a regex for parsing:

    // Setup regex
    $re = '/\[url=(?P<url>[^\]]*)](?P<song>[^\[]*)\[\/url]/';
    $str = '[url=https://www78.zippyshare.com/v/AQg3SYMQ/file.html]1. Like Im Fabo.mp3[/url][url=https://www78.zippyshare.com/v/TPRugyFb/file.html]2. Stic _Em Up.mp3[/url]';
    
    preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
    
    // Print the entire match result
    var_dump($matches);
    

    The output will be something like this:

    array(2) {
      [0]=>
      array(5) {
        [0]=>
        string(80) "[url=https://www78.zippyshare.com/v/AQg3SYMQ/file.html]1. Like Im Fabo.mp3[/url]"
        ["url"]=>
        string(49) "https://www78.zippyshare.com/v/AQg3SYMQ/file.html"
        [1]=>
        string(49) "https://www78.zippyshare.com/v/AQg3SYMQ/file.html"
        ["song"]=>
        string(19) "1. Like Im Fabo.mp3"
        [2]=>
        string(19) "1. Like Im Fabo.mp3"
      }
      [1]=>
      array(5) {
        [0]=>
        string(79) "[url=https://www78.zippyshare.com/v/TPRugyFb/file.html]2. Stic _Em Up.mp3[/url]"
        ["url"]=>
        string(49) "https://www78.zippyshare.com/v/TPRugyFb/file.html"
        [1]=>
        string(49) "https://www78.zippyshare.com/v/TPRugyFb/file.html"
        ["song"]=>
        string(18) "2. Stic _Em Up.mp3"
        [2]=>
        string(18) "2. Stic _Em Up.mp3"
      }
    }
    

    You can iterate through the result set like this:

    foreach ($matches as $match){
         echo(($match["url"])." => ".($match["song"])."\r\n");
    }
    

    And the result will be:

    https://www78.zippyshare.com/v/AQg3SYMQ/file.html => 1. Like Im Fabo.mp3
    https://www78.zippyshare.com/v/TPRugyFb/file.html => 2. Stic _Em Up.mp3