PHP preg_replace YouTube链接

时间:2015-07-13 18:46:48

标签: php regex

最好使用preg_replace向网址添加内容吗?目前我正在尝试获取YouTube视频并更改代码[视频]链接[/视频],例如使用preg_replace:

www.youtube.com/watch?v=6Zgp_G5o6Oc

并将其更改为

[video]www.youtube.com/watch?v=6Zgp_G5o6Oc[/video]

我应该使用preg_replace()还是有更好/更简单的方法?

1 个答案:

答案 0 :(得分:1)

假设您在变量中隔离了URL,请执行以下操作:

$taggedUrl = sprintf("[video]%s[/video]", $url);

或者:

$taggedUrl = "[video]" . $url . "[/video]";

或者:

$taggedUrl = "[video]{$url}[/video]";

但是,如果您需要在其他文本中找到该网址,preg_replace()将是合适的:

preg_replace('/((?:https?:\/\/)?www\.youtube\.com\/watch\?v=\w+)/', '[video]\1[/video]', $inputString);

例如:

php > $inputString = "osme regewgqg affbefqeif rgqbig www.youtube.com/watch?v=6Zgp_G5o6Oc sgwe\nhttps://www.youtube.com/watch?v=6ZrRpG_o6Oc wbqergq http://www.youtube.com/watch?v=6Zgp_G5o6Oc   gegrqe";
php > var_dump($inputString);
string(176) "osme regewgqg affbefqeif rgqbig www.youtube.com/watch?v=6Zgp_G5o6Oc sgwe
https://www.youtube.com/watch?v=6ZrRpG_o6Oc wbqergq http://www.youtube.com/watch?v=6Zgp_G5o6Oc   gegrqe"

php > var_dump(preg_replace('/((?:https?:\/\/)?www\.youtube\.com\/watch\?v=\w+)/', '[video]\1[/video]', $inputString));
string(221) "osme regewgqg affbefqeif rgqbig [video]www.youtube.com/watch?v=6Zgp_G5o6Oc[/video] sgwe
[video]https://www.youtube.com/watch?v=6ZrRpG_o6Oc[/video] wbqergq [video]http://www.youtube.com/watch?v=6Zgp_G5o6Oc[/video]   gegrqe"
php >

解释使用的正则表达式:

/.../    # Marks the start and end of the expression.
(...)    # Captures the entire match as \1
(?:...)? # ?: Makes a non-capturing group.
         # We put it in parenthesis to group this part of the expression.
         # The ? at the end makes the whole group optional
         # (so that http:// or https:// is not required at all, but matched if present)
https?   # Match either 'http' or 'https'.
\w+      # Matches one or more 'word characters' (0-9, a-z, A-Z, _)