2011-09-04 99 views
0

我有一堆看起來像這樣的聊天記錄:PHP:插入文字多達分隔符

name: some text 
name2: more text 
name: text 
name3: text 

我想強調的只是名字。我寫了一些代碼,應該這樣做,但是,我不知道是否有比這更清潔的方式:,

$line= "name: text"; 
$newtext = explode(":", $line,1); 
$newertext = "<font color=red>".$newtext[0]."</font>:"; 
$complete = $newertext.$newtext[1]; 
echo $complete; 
+1

順便說一下,標記已棄用! :)使用 ...另外,請記住,必須始終引用屬性!像。 – Qualcuno

+0

@Qualcuno我不知道:P 要快得多 – dukevin

+0

寫得更快,你的意思是?那麼,我們在2011年,這不是標準。你絕對應該避免它。 – Qualcuno

回答

1

看起來不錯,雖然你可以保存臨時變量:

$newtext = explode(":", $line,1); 
echo "<font color=red>$newtext[0]</font>:$newtext[1]"; 

這可能更快,也可能不會,你必須測試:

echo '<font color=red>' . substr_replace($line, '</font>', strpos($line, ':') , 0); 
+0

hm我得到'致命錯誤:只有變量可以通過引用傳遞' – dukevin

+0

@kevin my bad。我最後一個參數犯了一個錯誤。 str_replace的問題在於,你不能將它約束爲只做一個替換,所以這會導致在對話中使用的':'的其他出現。我用str_substr()更新了str_replace(這是一個選項),但由於這將是2個函數調用,我懷疑這可能不如爆炸效率高。 – gview

+0

我改變了程序的流程,而不是$ line逐行閱讀,整個文件被讀取和替換。這些解決方案僅取代第一條線,但對原始問題非常有用。 +1 – dukevin

0

也嘗試這樣的正則表達式:

$line = "name: text"; 
$complete = preg_replace('/^(name.*?):/', "<font color=red>$1</font>:", $line); 
echo $complete ; 

編輯

,如果他們的名字不是「名」或「名1」,只是在圖案刪除名稱,這樣

$complete = preg_replace('/^(.*?):/', "<font color=red>$1</font>:", $line); 
+0

問題是,我不知道每個人的名字是什麼。他們的名字不是「name」或「name1」 – dukevin

+0

然後試試這個而不是$ complete = preg_replace('/^(.*?):/',「 $ 1:」,$ line) ;由於某種原因, – steve

+0

,這顏色結束。 name: text dukevin

1

發表gview答案是簡單的它但是,只是作爲參考,您可以使用正則表達式來查找名稱標記,並使用preg_replace()將其替換爲新的html代碼,如下所示:

// Regular expression pattern 
$pattern = '/^[a-z0-9]+:?/'; 

// Array contaning the lines 
$str = array('name: some text : Other text and stuff', 
     'name2: more text : : TEsting', 
     'name: text testing', 
     'name3: text Lorem ipsum'); 

// Looping through the array 
foreach($str as $line) 
{ 
    // \\0 references the first pattern match which is "name:" 
    echo preg_replace($pattern, "<font color=red>\\0</font>:", $line); 
}