Created
October 13, 2022 12:23
-
-
Save RakibSiddiquee/d613168fda9eb71c057a30fd02a8c04e to your computer and use it in GitHub Desktop.
Format plain url to link and embed video in rich text editor content in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public function formatBody($value){ | |
// The Regular Expression filter | |
$reg_exUrl = '#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#'; | |
return Str::of($value)->replaceMatches($reg_exUrl, function ($match) { | |
$parsedUrl = parse_url($match[0]); | |
if (($parsedUrl['host'] == 'youtube.com' || $parsedUrl['host'] == 'www.youtube.com') && isset($parsedUrl['query'])) { | |
parse_str($parsedUrl['query'], $key); | |
return '<iframe allowfullscreen="true" src="https://www.youtube.com/embed/'.$key['v'].'?showinfo=0"></iframe>'; | |
} elseif ($parsedUrl['host'] == 'youtu.be' && isset($parsedUrl['path'])) { | |
return '<iframe allowfullscreen="true" src="https://www.youtube.com/embed/'.ltrim($parsedUrl['path'], '/').'?showinfo=0"></iframe>'; | |
} else { | |
return '<a href="' . $match[0] . '" target="_blank">' . $match[0] . '</a> '; | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment