dougai2427 2012-05-03 17:38
浏览 45
已采纳

PHP preg_replace:将Youtube链接替换为替换URL

in my website i have three regular expressions (one is disabled and you'll understand why...) to substitute what users posts:

1° Replace email with linked ones:

$string = preg_replace("/([\w-?&;#~=\.\/]+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?))/i","<a href=\"mailto:$1\">$1</a>",$string);

2° Replace Youtube link with embed video:

$pattern = '/http:\/\/www\.youtube\.com\/watch\?(.*?)v=([a-zA-Z0-9_\-]+)(\S*)/i';
$replace = '<iframe title="YouTube" class="youtube" type="text/html" width="320" height="240" src="http://www.youtube.com/embed/$2" frameborder="0" allowFullScreen></iframe>';
$string = preg_replace($pattern, $replace, $string);

3° Replace links with linked ones (these are disabled!):

 /*** make sure there is an http:// on all URLs ***/
$string = preg_replace("/([^\w\/])(www\.[a-z0-9\-]+\.[a-z0-9\-]+)/i", "$1http://$2",$string);
/*** make all URLs links ***/
$string = preg_replace("/([\w]+:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/i","<a target=\"_blank\" href=\"$1\">$1</a>",$string);

My problem is that, obviously, the third one substitute youtube links after they are replaced by previous regexp (switching sequence, break youtube videos)

How to enable third regexp to substitute URLs ignoring youtube pattern? Thank you ;-)

  • 写回答

1条回答 默认 最新

  • dongtang5229 2012-05-03 18:04
    关注

    Try this:

    // youtube
    $string = preg_replace("/\s*[a-zA-Z\/\/:\.]*youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i"," <object width=\"100%\" height=\"344\"><param name=\"movie\" value=\"http://www.youtube.com/v/$1&hl=en&fs=1\"></param><param name=\"allowFullScreen\" value=\"true\"></param><embed src=\"http://www.youtube.com/v/$1&hl=en&fs=1\" type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" width=\"100%\" height=\"450\"></embed></object>  ",$string);
    
    // email
    $string = preg_replace("/([\w-?&;#~=\.\/]+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?))/i","<a href=\"mailto:$1\">$1</a>", $string);
    
    // links
    $string = preg_replace("#(^|[
    \s>])([\w]+?://[^\s\"
    \t<]*)#is", "\\1<a href=\"\\2\">\\2</a>", $string);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效