2013-02-13 34 views
0

對於我的股票市場聊天,我想將每個特定的字符串模式替換爲html代碼。 例如,如果我輸入「B $ goog 780」我想這個字符串替換爲:將特定的字符串模式替換爲html

Buy <a href="/stocks/goog">$goog</a> at 780 

我如何做了preg_replace這個特定的任務嗎?

回答

2
$cmd='b $goog 780'; 

if(preg_match('/^([bs])\s+?\$(\w+?)\s+?(.+)$/i',$cmd,$res)) 
{ 
    switch($res[1]) 
    { 
    case 'b': $cmd='buy';break; 
    case 's': $cmd='sell';break; 
    } 
    $link=$cmd.' <a href="/stocks/'.$res[2].'">'.$res[2].'</a> at '.$res[3]; 
    echo $link; 
} 
+0

看起來正是我所需要的! – user1482261 2013-02-13 11:29:58

0
$stocks = array('$goog' => '<a href="/stocks/goog">$goog</a>', 
       '$apple' => '<a href="/stocks/apple">$apple</a>'); 

// get the keys. 
$keys = array_keys($stocks); 

// get the values. 
$values = array_values($stocks); 

// replace 
foreach($keys as &$key) { 
     $key = '/\b'.preg_quote($key).'\b/'; 
} 

// input string.  
$str = 'b $goog 780'; 

// do the replacement using preg_replace     
$str = preg_replace($keys,$values,$str); 
0

它是否有要的preg_replace?使用的preg_match可以提取字符串的組成部分,並重新組合它們形成你的鏈接:

<?php 
$string = 'b $goog 780'; 
$pattern = '/(b \$([^\s]+) (\d+))/'; 
$matches = array(); 
preg_match($pattern, $string, $matches); 
echo 'Buy <a href="/stocks/' . $matches[2] . '">$' . $matches[2] . '</a> at ' . $matches[3] ; // Buy <a href="/stocks/goog">$goog</a> at 780 

什麼模式是尋找,是字母「B」,其次是美元符號(\$ - 我們逃脫美元,因爲這是一個正則表達式中的特殊字符),然後任何和每個字符,直到它到達一個空間([^\s]+),然後一個空格,最後是任意數量的數字(\d+)。

相關問題