有没有办法从2个标签中提取文本,并以我选择的格式输出?

时间:2016-05-08 08:39:10

标签: javascript php jquery html text

有没有办法可以从2个标签中提取文字,并以我选择的格式输出?是否有可以执行此操作的应用程序或脚本?

例如:

[b]1.[/b] [artist]Norman Bass[/artist] – How U Like Bass? (Warp Brothers     Club Mix) [i](3:26)[/i]
[b]2.[/b] [artist]Rhythmkillaz[/artist] – Wack Ass M.F. (Payback Mix - Clean Version) [i](3:23)[/i]
[b]3.[/b] [artist]Mario Piu'[/artist] & [artist]DJ Arabesque[/artist] – The Vision (Vision 1 Mix) [i](3:41)[/i]
[b]4.[/b] [artist]Cosmic Gate[/artist] – Fire Wire (Club Mix) [i](2:47)[/i]
[b]5.[/b] [artist]Push[/artist] – Strange World (2000 Remake) [i](6:02)[/i]
[b]6.[/b] [artist]Cortina[/artist] – Music Is Moving (Kumara Mix) [i](3:40)[/i]
[b]7.[/b] [artist]Public Domain[/artist] – Operation Blade (Original Mix) [i](3:44)[/i]

我想在[artist]标签之间提取信息,并将其输出为一行,条目用逗号分隔。

那里有什么可以做到的吗?

4 个答案:

答案 0 :(得分:4)

在php中(使用RegEx):

<?php

function everything_in_tags($string, $tagname)
{
    $pattern = "#\[\s*?$tagname\b[^>]*\](.*?)\[/$tagname\b[^>]*\]#s";
    preg_match($pattern, $string, $matches);
    return $matches[1];
}

?>

这里我们指定标记名&amp; b / w获取数据。

参考:get everthing between and with php

在jQuery中:

var regExp = /\]([^\[]+)\[/;
var matches = regExp.exec("[article]I expect five hundred dollars ($500).[/article]");

//matches[1] contains the value between the parentheses
console.log(matches[1]);

这与]&amp;之间的任何内容相匹配[并将其记录在控制台上。

我们在这里搜索字符串中除[以外的任何内容。

jQuery解决方案:fiddle

答案 1 :(得分:2)

这是Javascript中简单的正则表达式:

var re = /\[artist\].+?(?=\[\/artist\])/g,
    artists = str.match(re).map(s => s.substr(8)),
    output = artists.join(', ');

如果您需要更多功能的东西,可以在功能中封装相同的方法:

function getTag(str, tagName){
    var re = new RegExp(`\\[${tagName}\\].+?(?=\\[\\/${tagName}\\])`, 'g');
    return str.match(re).map(s => s.substr(tagName.length + 2));
}

getTag(str, 'artist').join(', '); 

» Fiddle
Regex 101: explanation

答案 2 :(得分:1)

我想这应该这样做

var dataStr = "[b]1.[/b] [artist]Norman Bass[/artist] – How U Like Bass? (Warp Brothers     Club Mix) [i](3:26)[/i]\n[b]2.[/b] [artist]Rhythmkillaz[/artist] – Wack Ass M.F. (Payback Mix - Clean Version) [i](3:23)[/i]\n[b]3.[/b] [artist]Mario Piu'[/artist] & [artist]DJ Arabesque[/artist] – The Vision (Vision 1 Mix) [i](3:41)[/i]\n[b]4.[/b] [artist]Cosmic Gate[/artist] – Fire Wire (Club Mix) [i](2:47)[/i]\n[b]5.[/b] [artist]Push[/artist] – Strange World (2000 Remake) [i](6:02)[/i]\n[b]6.[/b] [artist]Cortina[/artist] – Music Is Moving (Kumara Mix) [i](3:40)[/i]\n[b]7.[/b] [artist]Public Domain[/artist] – Operation Blade (Original Mix) [i](3:44)[/i]",
   selected = dataStr.match(/[^\]]+(?=\[\/a)/g).join(", ");
document.write(selected);

答案 3 :(得分:0)

preg_match_all("/\[artist\](.*?)\[\/artist\]/", $str, $out);

For($i=0;$i<=count($out[1]);$i++){
   Echo $out[1][$i] . ",";
}

http://www.phpliveregex.com/p/fBW