我有一个包含链接的字符串。我希望我的PHP可以根据链接对链接执行不同的操作。使用PHP查找字符串中的链接。与普通和youtube链接不同
答:
所有的function fixLinks($text)
{
$links = array();
$text = strip_tags($text);
$pattern = '!(https?://[^\s]+)!';
if (preg_match_all($pattern, $text, $matches)) {
list(, $links) = ($matches);
}
$i = 0;
$links2 = array();
foreach($links AS $link) {
if(strpos($link,'youtube.com') !== false) {
$search = "!(http://.*youtube\.com.*v=)?([a-zA-Z0-9_-]{11})(&.*)?!";
$youtube = '<a href="youtube.php?id=\\2" class="fancy">http://www.youtube.com/watch?v=\\2</a>';
$link2 = preg_replace($search, $youtube, $link);
} else {
$link2 = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\-\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1" target="_blank"><u>$1</u></a>', $link);
}
$links2[$i] = $link2;
$i++;
}
$text = str_replace($links, $links2, $text);
$text = nl2br($text);
return $text;
}
'eregei'什么? –
我会更努力,并将更多的正则表达式放在它上面。这通常有助于完全消除视线内任何东西:) - 这有一个回调,所以你可以先提取所有链接,然后寻找youtube:http://stackoverflow.com/questions/6861324/how-to-extract-http -a-paragraph-and-store-them-in-a-array-on-php/6861706#6861706 - 此处为youtube正则表达式:http:// stackoverflow。com/questions/6556559/youtube-api-extract-video-id/6556662#6556662 – hakre
嗯,这只是我发现的一些来的测试。我很乐意提供建议。谢谢 – Holsteinkaa