I need to capture an ID that is part of a URL that is inside an iframe tag. I know this can be done with regex but I'm not very good at it, I made a few attempts but could not get a result, iframe would be this (ID may vary):
<iframe src="https://www.example.com/embed/ph57d6z9fa1349b" frameborder="0" height="481" width="608" scrolling="no"></iframe>
And the ID I would like to get would be this:
ph57d6z9fa1349b
You can split the string with the regex.
$re = '/\<iframe[^\>]+src\="(.+?)\/([A-Za-z0-9]+)"/';
$str = '<iframe src="https://www.example.com/embed/ph57d6z9fa1349b" frameborder="0" height="481" width="608" scrolling="no"></iframe>';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
If you want to list id codes (like 'ph57d6z9fa1349b') then you can do this:
<?php
$re = '/\<iframe[^\>]+src\="(.+?)\/([A-Za-z0-9]+)"/';
$str = '<iframe src="https://www.example.com/embed/ph57d6z9fa1349b" frameborder="0" height="481" width="608" scrolling="no"></iframe>';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
foreach ($matches as $match) {
$id = $match[2]; // The required id code
echo $id; // Echo it
}
?>