【发布时间】:2011-12-08 15:44:26
【问题描述】:
普通链接
$content = preg_replace('@(https?://([-\w\.]+)+(:\d+)?((/[\w/_\.%\-+~]*)?(\?\S+)?)?)@', '<a href="$1" target="_blank">$1</a>', $content);
下载链接
$content = preg_replace('@(https?://([-\w\.]+)+(:\d+)?/[\w/_\.%\-+~]+(\.exe|\.mp3|\.pdf|\.rar|\.doc|\.jar|\.ppt|\.xls|\.png|\.jpg|\.jpeg|\.gif|\.mp4|\.avi|\.mkv|\.flv|\.3gp|\.mms|\.sis|\.sisx|\.jad|\.mdi|\.qcp)(\?\S+)?)@', '<a href="$1" target="_blank">Download</a>', $content);
对于 Youtube 链接
// Replace Youtube URLs with embed code
function embedYoutube($text)
{
$search = '% # Match any youtube URL in the wild.
(?:https?://)? # Optional scheme. Either http or https
(?:www\.)? # Optional www subdomain
(?: # Group host alternatives
youtu\.be/ # Either youtu.be,
| youtube\.com # or youtube.com
(?: # Group path alternatives
/embed/ # Either /embed/
| /v/ # or /v/
| /watch\?v= # or /watch\?v=
) # End path alternatives.
) # End host alternatives.
([\w\-]{10,12}) # Allow 10-12 for 11 char youtube id.
\b # Anchor end to word boundary.
%x';
$replace = '<object width="425" height="344">
<param name="movie" value="http://www.youtube.com/v/$1?fs=1"</param>
<param name="allowFullScreen" value="true"></param>
<param name="allowScriptAccess" value="always"></param>
<embed src="http://www.youtube.com/v/$1?fs=1"
type="application/x-shockwave-flash" allowscriptaccess="always" allowFullScreen="true" width="425" height="344">
</embed>
</object>';
return preg_replace($search, $replace, $text);
}
我正在使用它,但我想将所有这些应用到相同的文本上,同时不影响彼此的输出。
例如
$content = "Download this song http://songs.com/song1.mp3
Watch it Video http://www.youtube.com/watch?v=YR12Z8f1Dh8
and click here for more details http://en.wikipedia.org/wiki/Song"
会产生这个
Download this song <br />
<a href="http://songs.com/song1.mp3" target="_blank">Download</a>
Watch it Video <br />
<object width="425" height="344">
<param name="movie" value="http://www.youtube.com/v/YR12Z8f1Dh8?fs=1"</param>
<param name="allowFullScreen" value="true"></param>
<param name="allowScriptAccess" value="always"></param>
<embed src="http://www.youtube.com/v/YR12Z8f1Dh8?fs=1"
type="application/x-shockwave-flash" allowscriptaccess="always" allowFullScreen="true" width="425" height="344">
</embed> </object>
and click here for more details <br />
<a href="http://en.wikipedia.org/wiki/Song" target="_blank">http://en.wikipedia.org/wiki/Song</a>
我可以用一个通用的正则表达式或任何 PHP 方法来解决这个问题吗?
【问题讨论】:
-
请提供一些输入示例,在运行正则表达式之前,您在 $context 变量中拥有这些示例。
-
每个链接的行是否总是换行?
-
@SebastiánGrignoli 示例现已提供
-
没有人回答吗
标签: php regex algorithm youtube preg-replace