将包含方括号标签及其标签的字符串解析为数组

问题描述 投票:0回答:3

我已经构建了以下代码,它正在执行我的代码的数组部分所需的操作。

$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>';

以上部分返回此。

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
)

我现在想知道如何分解上面的每个部分以返回这样的东西。

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
)

这样我就可以轻松获取文件路径和文件名。

php text-parsing
3个回答
2
投票

您可以使用正则表达式进行解析:

// 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);

输出将是这样的:

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"
  }
}

您可以像这样迭代结果集:

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

结果将是:

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

0
投票

首先使用 trim 修剪字符串前面的 [url= 然后用 ]

分解字符串的其余部分

-1
投票

您应该循环遍历数组,并使用 parse_url() 函数解析每个 URL。

© www.soinside.com 2019 - 2024. All rights reserved.