Javascript code inside HTML code inside PHP string

Solution:

Your example is working. Here is a formatted version of it. I run it on a PHP Sandbox without any problem. The only adjustment was to change the greedy selector .* to a non-greedy one .*?.

I’m guessing, your generated JavaScript code is the problem here. The generated JavaScript code is not valid. You need to escape everything in $1 and surround it with brackets.

Here is a formatted version of your code.

<?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"];
?>

And here is the output of this code:

<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>

If you need further help, please provide a comment below.