2010-10-04 24 views
1

我在我的應用程序中有自定義html標記,它看起來像這樣:<wiki href="articletitle">Text</wiki>並且希望它被替換爲像這樣:<a href="http://myapps/page/articletitle">Text</a>。我如何在PHP中做到這一點?取代php中的自定義html標記

+0

誰的代碼正在創建這些自定義標籤? – egrunin 2010-10-04 02:05:40

回答

1

Ruel是正確的,DOM解析是正確的方法來處理它。作爲正則表達式的鍛鍊,然而,這樣的事情應該工作:

<?php 
$string = '<wiki href="articletitle">Text</wiki>'; 
$pattern = '/<wiki href="(.+?)">(.+?)<\/wiki>/i'; 
$replacement = '<a href="http://myapps/page/$1">$2</a>'; 
echo preg_replace($pattern, $replacement, $string); 
?> 
+1

你應該至少讓量詞懶惰,否則這會炸掉。 – 2010-10-04 07:20:49

+0

謝謝 - 已經完成。 – tagawa 2010-10-27 09:56:27

0

trying to do something very similar。我建議避免像瘟疫一樣的regEx。它從來沒有像看起來那麼容易,而這些角落案件會引起噩夢。

現在我傾向於Custom Tags圖書館mentioned in this post。最好的一個特點是如下面的代碼塊掩埋或嵌套標籤的支持:

<ct:upper type="all"> 
    This text is transformed by the custom tag.<br /> 
    Using the default example all the characters should be made into uppercase characters.<br /> 
    Try changing the type attribute to 'ucwords' or 'ucfirst'.<br /> 
    <br /> 
    <ct:lower> 
     <strong>ct:lower</strong><br /> 
     THIS IS LOWERCASE TEXT TRANSFORMED BY THE ct:lower CUSTOM TAG even though it's inside the ct:upper tag.<br /> 
     <BR /> 
    </ct:lower> 
</ct:upper> 

我強烈建議下載zip文件,並通過它包含的例子看。