我正在尝试将字符串中的文本转换为表情符号。我已经尝试过并且成功了一半。
问题: 当我将字符串中的字符替换为表情符号时,链接http://mywebsite.com中的字符“:/”也会被替换。
到目前为止我做了什么:
chat.php
<?php
require('common.php');
if($_POST && !empty($_POST['title'])){
$result = $db->add_news($_POST['title']);
}
$text="";
function parseSmiley($text){
//Smiley to image
$smileys=array('o:)'=>'angel.gif', ':3'=>'colonthree.gif', 'o.O'=>'confused.gif', ":'("=>'cry.gif', '3:)'=>'devil.gif', ':('=>'frown.gif', ':O'=>'gasp.gif', '8)'=>'glasses.gif', ':D'=>'grin.gif', ">:-("=>'grumpy.gif', '<3'=>'heart.gif', '^_^'=>'kiki.gif', ':*'=>'kiss.gif', ':v'=>'pacman.gif', ':)'=>'smile.gif', '-_-'=>'squint.gif', '8|'=>'sunglasses.gif', ':p'=>'tongue.gif', ':/'=>'unsure.gif', '>:-O'=>'upset.gif', ';)'=>'wink.gif');
//Now you need to find and replace
foreach($smileys as $smiley=>$img){
$text=str_replace(htmlspecialchars($smiley), "<img src='emotions-fb/{$img}'/>", $text);
}
//Now only return it
return $text;
}
?>
db.php中
function get_news(){
if($result = $this->db->query('SELECT * FROM news WHERE id<>1 ORDER BY add_date DESC LIMIT 50')){
$return = '';
while($r = $result->fetch_object()){
$timing=explode(" ", $r->add_date);
$return .= '<p>'.wordwrap(htmlspecialchars($r->title), 25, "\n", true).'</p>';
//$return .='<p>'.$timing[1].' on '.$timing[0].'</p>';
$return .= '<hr/>';
}
return $return;
}
}
之后我搜索了stackoverflow并得到了类似的东西,但这并没有取代任何文字到图像
foreach($smileys as $smiley=>$img){
$smiley=preg_quote($smiley);
$text=preg_replace("~\b$smiley\b~", "<img src='emotions-fb/{$img}'/>", $text);
}
我不知道我哪里出错了。 提前谢谢。
答案 0 :(得分:0)
尝试:
$smileys=array('o:)'=>'angel.gif', ':3'=>'colonthree.gif', 'o.O'=>'confused.gif', ":'("=>'cry.gif', '3:)'=>'devil.gif', ':('=>'frown.gif', ':O'=>'gasp.gif', '8)'=>'glasses.gif', ':D'=>'grin.gif', ">:-("=>'grumpy.gif', '<3'=>'heart.gif', '^_^'=>'kiki.gif', ':*'=>'kiss.gif', ':v'=>'pacman.gif', ':)'=>'smile.gif', '-_-'=>'squint.gif', '8|'=>'sunglasses.gif', ':p'=>'tongue.gif', ':/'=>'unsure.gif', '>:-O'=>'upset.gif', ';)'=>'wink.gif');
$text='Some example text with smile :/ ^_^ and :\'( and link <a href="http://google.com"> my site :/</a>';
foreach ($smileys as $smiley => $img)
{
$smiley = preg_quote( $smiley );
$text = preg_replace( "#(?<=\s|^)(?:$smiley)(?=\s|$)?#i", '<img src="emotions-fb/'. $img .'">', $text);
}
echo $text;