单独的YouTube,可下载的,和简单的URL链接从相同的文本在PHP


Separate YouTube, Downloadable, and simple URL link from same text in PHP

正常链接

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

For Youtube Link

// 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方法来解决这个问题吗?

我会使用preg_match_allPREG_OFFSET_CAPTURE选项来查找所有带有偏移量的URL,重写每个URL,使用偏移量提取插页文本,并将所有内容放回一起