将url转换为格式化文本上的超链接


convert url to hyperlink on text as formatted

我使用以下代码将url转换为文本上的超链接。但问题是,我想使用超链接的缩略标题例如,这是url http://stackoverflow.com/questions/ask?title=convert%20url%20to%20hyperlink%20on%20text%20as%20formatted转换后像这样:

<a href="http://stackoverflow.com/questions/ask?title=convert%20url%20to%20hyperlink%20on%20text%20as%20formatted">http://stackoverflow.com/questions/ask?title=convert%20url%20to%20hyperlink%20on%20text%20as%20formatted</a>

I want to this:

<a href="http://stackoverflow.com/questions/ask?title=convert%20url%20to%20hyperlink%20on%20text%20as%20formatted">http://stackoverflow.com/...</a>

这是我的代码:

$stringdata = preg_replace('|(['w'd]*)'s?(https?://(['d'w'.-]+'.['w'.]{2,6})[^'s']'['<'>]*/?)|i', '$1 <a href="$2" target="_blank">$2</a>', $stringdata);

标题应缩短,但url应与原文相同。

谢谢。

你可以使用这里的parse_url

下面是一个例子:

$url = 'http://www.stackoverflow.com/questions/ask?title=convert%20url%20to%20hyperlink%20on%20text%20as%20formatted';
$splitUrl = parse_url($url);
echo '<a href="' . $url . '"/>' . $splitUrl['scheme'] . '://' . $splitUrl['host'] .'/... </a>';

parse_url根据提供的URL创建数组。

更新:根据Mikael Roos在那个链接上的回答,我想出了你需要它做什么。

function make_clickable($text) {
    $regex = '#'bhttps?://[^'s()<>]+(?:'(['w'd]+')|([^[:punct:]'s]|/))#';
    return preg_replace_callback($regex, function ($matches) {
        $splitUrl = parse_url($matches[0]);
        return "<a href='{$matches[0]}'>{$splitUrl['scheme']}://{$splitUrl['host']}/..</a>";
    }, $text);
}
echo make_clickable('Some odd text here that makes https://stackoverflow.com/questions/ask?title=convert%20url%20to%20hyperlink%20on%20text%20as%20formatted clickable');

try this

$var='http://stackoverflow.com/questions/ask?title=convert%20url%20to%20hyperlink%20on%20text%20as%20formatted';
$array=explode('/', $var);
$url=$array[0]."//".$array[2]."/...";