在函数中转换文本的微笑和链接


Converting smiles and links of a text in a function

我正在尝试将笑脸符号转换为图像,并在函数中将链接转换为锚点我尝试了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://请帮助提前感谢:-)

更改以下内容:$smiles = array(':/' => 'E:''smiles''sad.jpg');

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

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

您可以使用正则表达式解决此问题:

更改此设置:

$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);