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://请帮助提前感谢:-)

4

2 回答 2

0

改变这个: $smiles = array(':/' => 'E:\smiles\sad.jpg');

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

注意笑脸前后的空间。现在它不再匹配 http:/ 了。

于 2013-10-15T12:07:11.837 回答
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);
于 2013-10-15T12:11:24.700 回答