2011-10-29 58 views
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+。

回答

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

這看起來像一個整潔的解決方案,想知道爲什麼我沒有考慮過之前。它比正則表達式更快/更好嗎? –

+1

@RiMMER:他們都應該是線性時間,但這個解決方案可能會更快,因爲開銷較少。像正則表達式一樣有趣,他們並不總是在實踐中的正確答案:) – Cam

+0

嗯,這絕對看起來像最好的解決方案,但我會等待別人投票之前,我接受任何東西,我希望這與大家:)行動 –

0

嘗試

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

小心的HTML代碼或畸形[]在你輸入的字符串不過,

0

模式

\[(.*?)\] 

替換

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

所有的正則表達式都會使用,所以你要小心使用不好的[]對,如果歌詞可能以某種方式包含[那麼你會想要正確地逃避它。

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 «\]» 
相關問題