I have a text input field for a user to input a video url, for example: https://www.youtube.com/watch?v=d4bv2NaO9fQ (this is just a video I selected at random to test)
I then want to extract the id from the url to use to embed the video. I've been following KAD's example using regex here: How to embed YouTube videos in PHP?
In the code below I am taking $videourl from a customizer field in WordPress and trying to apply the regex to it, but it just returns an empty array. If I swap out $videourl for the hardcoded $url1 that you can see in the code below, then it works perfectly.
As you can see I am echoing both the urls and what that returns looks identical:
<div>
https://www.youtube.com/watch?v=d4bv2NaO9fQ </div>
<div>
https://www.youtube.com/watch?v=d4bv2NaO9fQ </div>
<?php
$customizer_video_repeater = get_theme_mod('video-repeater', json_encode( array()) );
$customizer_video_repeater_decoded = json_decode($customizer_video_repeater);
foreach($customizer_video_repeater_decoded as $repeater_item){
$videourl = $repeater_item->text;
?>
<div class="videocontainer">
<div class="videoresponse">
<?php
if ($videourl) {
?>
<div>
<?php echo $videourl ?>
</div>
<?php
$url1 = "https://www.youtube.com/watch?v=d4bv2NaO9fQ";?>
<div>
<?php echo $url1 ?>
</div>
<?php
preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user|shorts)\/))([^\?&\"'>]+)/u", $videourl , $matches);
print_r ($matches);
?>
<iframe width="356" height="200" src="https://www.youtube.com/embed/<?php echo $matches[1] ?>" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<?php } ?>
</div>
</div>
<?php } ?>
I don't know if it coming from an input field means it is encoded incorrectly for regex in some way? I've looked at the answer to a similar question here: Input from form doesn't match regex, but hard-coded string does
and added the /u to the end of my preg_match but it doesn't seem to have made any difference.
Any ideas would be a great help, thanks!