regex - PHP preg_replace YouTube Links -


is best use preg_replace add things urls? trying youtube video , change replace code [video] link [/video], example using preg_replace:

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

and changing to

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

so should use preg_replace() or there better/easier method?

assuming have url isolated in variable, this:

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

or:

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

or:

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

but, if need find url inside other text, preg_replace() appropriate:

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

for example:

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 > 

to explain regex used:

/.../    # marks start , end of expression. (...)    # captures entire match \1 (?:...)? # ?: makes non-capturing group.          # put in parenthesis group part of expression.          # ? @ end makes whole group optional          # (so http:// or https:// not required @ all, matched if present) https?   # match either 'http' or 'https'. \w+      # matches 1 or more 'word characters' (0-9, a-z, a-z, _) 

Comments

Popular posts from this blog

searchKeyword not working in AngularJS filter -

sequelize.js - Sequelize: sort by enum cases -

user interface - how to replace an ongoing process of image capture from another process call over the same ImageLabel in python's GUI TKinter -