1

Is it best to use preg_replace to add things to urls? Currently I am trying to get a youtube video and change replace it with the code [video] link [/video], for example using preg_replace:

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

and changing it to

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

So should I use preg_replace() or is there a better/easier method?

2
  • you can, but why don't use your parse_url/parse_str to do it for you? Commented Jul 13, 2015 at 18:48
  • 1
    if $sptr = "www.youtube.com/watch?v=6Zgp_G5o6Oc"; then only $str = '[video]' . $str.'[video]'; Commented Jul 13, 2015 at 18:50

1 Answer 1

1

Assuming you have the URL isolated in a variable, just do this:

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

Or:

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

Or:

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

But, if you need to find the URL inside other text, preg_replace() would be 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 the regex used:

/.../    # 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, _)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.