Solution:
Your example is basically correct, but it needs a couple of adjustments:
Change the greedy selector .* to a non-greedy version .*? so it won’t overmatch.
Fix the generated JavaScript. The $1 placeholder is inserted literally, which makes the JavaScript invalid. You’ll need to escape it properly and pass it as a string.
<?php
$record = array("DESCRIPTION" => '<iframe src="http://www.google.com"></iframe>');
$replacement = '$1<br>';
$replacement .= '<button type="button" onclick="download()">تحميل</button>';
$replacement .= '<script>';
$replacement .= 'function download() {';
$replacement .= ' APP.CallSub("download", true, YouTubeGetID(\'$1\'));';
$replacement .= '}';
$replacement .= 'function YouTubeGetID(url){';
$replacement .= ' var ID = "";';
$replacement .= ' url = url.replace(/(>|<)/gi,"").split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);';
$replacement .= ' if(url[2] !== undefined) {';
$replacement .= ' ID = url[2].split(/[^0-9a-z_\-]/i);';
$replacement .= ' ID = ID[0];';
$replacement .= ' } else {';
$replacement .= ' ID = url;';
$replacement .= ' }';
$replacement .= ' return ID;';
$replacement .= '}';
$replacement .= '</script>';
$record["DESCRIPTION"] = preg_replace(
"/(<iframe.*?<\/iframe>)/U",
$replacement,
$record["DESCRIPTION"]
);
echo $record["DESCRIPTION"];
?>
Output
<iframe src="http://www.google.com"></iframe><br>
<button type="button" onclick="download()">تحميل</button>
<script>
function download() {
APP.CallSub("download", true, YouTubeGetID('<iframe src="http://www.google.com"></iframe>'));
}
function YouTubeGetID(url){
var ID = "";
url = url.replace(/(>|<)/gi,"").split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
if(url[2] !== undefined) {
ID = url[2].split(/[^0-9a-z_\-]/i);
ID = ID[0];
} else {
ID = url;
}
return ID;
}
</script>