2013-10-15 32 views
0

我想將笑臉符號轉換成圖像並鏈接到函數中的錨點 我嘗試了10次以上解決,但不能, 我是新的PHP。轉換函數中的文本的笑臉和鏈接

這裏是我的代碼:

<?php 
$text = "hey :/ Theere is 2 links andc3 smiles in this text http://google.com then trun nto http://yahoo.com"; 


function cust_text($string) 
{ 
$content_array = explode(" ", $string); 
$output = ''; 

foreach($content_array as $content) 
{ 

// check word starts with http:// 
if(substr($content, 0, 7) == "http://") 
$content = '<a href="' . $content . '">' . $content . '</a>'; 

//starts word with www. 
if(substr($content, 0, 4) == "www.") 
$content = '<a href="http://' . $content . '">' . $content . '</a>'; 

$output .= " " . $content; 

} 
output = trim($output); 

$smiles = array(':/' => 'E:\smiles\sad.jpg'); 
foreach($smiles as $key => $img) { 

$msg = str_replace($key, '<img src="'.$img.'" height="18" width="18" />',  $output);} 

return $msg; 
} 

echo cust_text($text); 

?> 

在結果的笑臉代替:/ HTTP中:// 請幫助 由於事先:-)

+0

你不應該鏈接到E:\。當你把腳本放到網上時,你只能看到笑臉。你應該對你的笑臉做一個「相對鏈接」:src =「directory/smiley.jpg」 – Veda

回答

0

更改此: $微笑=陣列(':/'=>'E:\ smiles \ sad.jpg');

in this: $ smiles = array(':/'=>'E:\ smiles \ sad.jpg');

請注意笑臉前後的空間。現在它不會匹配http:/了。

0

你可以用正則表達式解決這個問題:

更改此:

$msg = str_replace($key, '<img src="'.$img.'" height="18" width="18" />',  $output); 

成這樣:

$msg = preg_replace('~'.preg_quote($key).'(?<!http:/)~', '<img src="'.$img.'" height="18" width="18" />', $output); 

但我必須說,對於一個初學者,這不是最簡單的解決方案。

這在正則表達式中使用了「否定後視」表達式。這與字符串替換大致相同,不同之處在於它回頭看看是否:/不是http的一部分:/ 這兩個字符是正則表達式的起始和結束符。如果你想包含一個笑臉了〜你需要逃避它,像這樣:\〜

您可以用str_replace函數解決這個問題:

$key = str_replace('~', '\~', $key);