I have a text that contains youtube URLs.I want to convert all youtube URLs to embed code. For example :
From
To
* Sample
++++
<iframe width="560" height="315" src="https://www.youtube.com/embed/S-thTTqefls?start=60" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
++++
* Sample
++++
<iframe width="560" height="315" src="https://www.youtube.com/embed/xcJtL7QggTI?start=60" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
++++
First Method
I want to push the matched youtube URL between the embed code.But I don't know how can I do this?
> "++++\n" + "<iframe width=\"560\" height=\"315\" src=\"" + How can I
> push URL here with following code?
> + "\" frameborder=\"0\" allow=\"autoplayencrypted-media\" allowfullscreen></iframe>\n++++"
String Content = readFileAsString(Path); Pattern MY_PATTERN = Pattern.compile("^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)\/.+$"); Matcher m = MY_PATTERN.matcher(Content); Content = m.replaceAll("++++\n" + "\n++++");
Content = Content.replace("youtu.be", "youtube.com/embed");
Content = Content.replace("?t=", "?start=");
Second Method
I tried to place embed code by finding all youtube URL in the loop and placing embed code bu substring method.
"\n++++\n<iframe width=\"560\" height=\"315\" src=\""
44 character
https://youtu.be/S-thTTqefls?t=60
max 34 chracter
for (int i = -1; (i = Content.indexOf("https://youtu.be", i + 1)) != -1; i++) {
Content = Content.substring(0, i) + "\n++++\n<iframe width=\"560\" height=\"315\" src=\"" + Content.substring(i, Content.length());
Content = Content.substring(0, i + 78) + "\" frameborder=\"0\" allow=\"autoplay; encrypted-media\" allowfullscreen></iframe>\n++++\n" + Content.substring(i + 78, Content.length());
}
Content = Content.replace("youtu.be", "youtube.com/embed");
Content = Content.replace("?t=", "?start=");
But some https://youtu.be URLs do not get an embed code. But I have a weird output like this.
> ++++ <iframe width="560" height="315" src="
> ++++ <iframe width="560" height="315" src="<iframe width="560" height="315" src="
> ++++ <iframe width="560" height="315" src=" https://youtube.com/watch?v=xcJtL7QggTI?t=60" frameborder="0"
> allow="autoplay; encrypted-media" allowfullscreen></iframe>
> ++++
>
> " frameborder="0" allow="autoplay; encrypted-media"
> allowfullscreen></iframe>
> ++++
>
> " frameborder="0" allow="autoplay; encrypted-media"
> allowfullscreen></iframe>
> ++++