2010-07-02 53 views
1

如何將包含單詞和句子的文本從一段文本轉換爲帶有PHP的斜體標籤。提前致謝。將周圍的下劃線轉換爲標籤

所以 -

This is _just_ a test string for the _purposes of this example_. 

將成爲 -

This is <i>just</i> a test string for the <i>purposes of this example</i>. 

回答

1

基本上使用正則表達式。請注意,如果下劃線出現在別處,這可能會產生不希望的效果,例如,在預先存在的HTML標籤和URL中。如果是這樣,你也必須嘗試\ b。或者,使用現成的Wiki解析器,如果這就是你所需要的。

+0

感謝馬里奧和蜥蜴,他們都很好,但我喜歡這個的簡短。你能推薦任何學習regulr表達的好地方嗎? – usertest 2010-07-02 16:31:18

+0

@ user201140:我最喜歡的資源是http://www.regular-expressions.info/javascriptexample.html;它具有Perl和PHP regex meta thingys的廣泛概述,並且通常比PHP手冊或Perl手冊頁更容易理解。這通常是谷歌首次在該領域進行任務。無論如何,嘗試正則表達式測試工具。還有更多,甚至桌面正則表達式構建器/測試器。 – mario 2010-07-02 16:56:43

2
$content = "This is _just_ a test string for the _purposes of this example_."; 

preg_match_all("|_(.*)_|U",$content,$rows); 

foreach($rows[0] as $key=>$row) { 
    $content = str_replace($row, "<i>".$rows[1][$key]."</i>", $content); 
} 
echo $content; 

這是只是測試字符串爲目的這個例子的。