我如何使用正则表达式来解析这个和弦方案?

时间:2011-10-29 02:19:11

标签: php regex

以下列输入为例:

[Ami]Song lyrics herp derp [F]song lyrics continue
[C7/B]Song lyrics continue on another [F#mi7/D]line

我需要解析上面的内容并将其回显如下:

<div class="chord">Ami</div>Song lyrics herp derp <div class="chord">F</div>song lyrics continue
<div class="chord">C7/B</div>Song lyrics continue on another <div class="chord">F#mi7/D</div>line

所以基本上,我需要:

1)将[更改为<div class="chord">

2)然后附加括号内容

3)然后将]更改为</div>

...使用PHP 5.3 +。

4 个答案:

答案 0 :(得分:10)

这会奏效。

$tab = "[Ami]Song lyrics herp derp [F]song lyrics continue
[C7/B]Song lyrics continue on another [F#mi7/D]line";

echo str_replace(
    array('[', ']'),
    array('<div class="chord">','</div>'),
    $tab
);

答案 1 :(得分:2)

$result = preg_replace('/\[(.*?)\]/', '<div class="chord">\1</div>', $subject);

# \[(.*?)\]
# 
# Match the character “[” literally «\[»
# Match the regular expression below and capture its match into backreference number 1 «(.*?)»
#    Match any single character that is not a line break character «.*?»
#       Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
# Match the character “]” literally «\]»

答案 2 :(得分:0)

echo preg_replace('#\\[([^]]*)\\]#','<div class="chord">$1</div>',$string);

请注意输入字符串中的HTML代码或格式错误的[]

答案 3 :(得分:0)

模式

 \[(.*?)\]

替换为

<div class="chord">$1</div>

正如所有正则表达式一样,你要小心使用坏[]对,如果歌词可能以某种方式包含[那么你会想要正确地逃避它。