将带链接的文本转换为可点击 - 错误

时间:2018-03-30 19:27:17

标签: php

基于此post

我有以下几乎可以工作的代码,但clean正在返回错误

  

语法错误,意外' 0' (T_LNUMBER)

$url = '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i';
$clean = str_replace(['https://', 'http://', 'www.'], '', $0);
$html = '<a href="$0" target="_blank" title="$0">'.$clean.'</a>';
$questionLinks = preg_replace($url, $html, $question->question);

问题在于$ 0,我怎样才能使用正常变量?

1 个答案:

答案 0 :(得分:1)

试试这个:

$url = '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i';
preg_match($url, $question->question, $completeUrl);
$clean = preg_replace('~^www.~', '', $completeUrl[2]);
$http = strpos($question->question, 'http');
$html = ($http ? '<a href="$0" target="_blank" title="$0">'.$clean.'</a>' : '<a href="http://$0" target="_blank" title="$0">$0</a>');
$questionLinks = preg_replace($url, $html, $question->question);