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

10

考虑以下输入作为一个例子:

[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个回答

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

看起来这是一个不错的解决方案,不知道为什么我以前没有想到过。它比正则表达式更快/更好吗? - Frantisek
1
@RiMMER:它们都应该是线性时间,但这个解决方案可能会更快,因为开销较小。尽管正则表达式很有趣,但在实践中它们并不总是正确的答案 :) - Cam
好的,这肯定看起来是最好的解决方案,但在我接受任何东西之前,我会等待其他人的投票,希望大家都没问题 :) - Frantisek
查看http://www.php-scripts.com/php_diary/011303.php3 - 我认为这样更容易理解你要替换什么。 - Book Of Zeus

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 «\]»

0

模式

 \[(.*?)\]

替换为

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

就像所有正则表达式使用一样,您需要小心处理不良的[]对,如果歌词中包含[,则需要正确转义。


0

尝试

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

在编程中要注意输入字符串中的HTML代码或格式不正确的[]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接