'PHP nl2br for text content but make it exclude on javascript content

I need to use nl2br function on page content coming from DB. But <br /> tag added to into javascript content too.

<script type="text/javascript"><br />
let test = "test";<br />
let menu = "menu";<br />
</script>

Firstly for make add br to all content and than remove br from javascript content, I did try this:

<?php
//content coming from db
$content = nl2br($content);
$content = preg_replace("/<script\b[^>]*>([\s\S]*?)<\/script\b[^>]*>/m", str_replace("<br />", "", nl2br($content)), $content);
echo $content;
?>

Result: br not added into javascript but javascript and text content did come twice (br didn't worked on first text content but worked on second text content)

How can I exclude br in javascript code?



Solution 1:[1]

Assuming your regex suites your need, you can use preg_replace_callback to achieve what you want.

//content coming from db
$content = preg_replace_callback("/<script\b[^>]*>([\s\S]*?)<\/script\b[^>]*>/m",function($matches){return str_replace('<br />','',$matches[0]);},nl2br($content));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 keyhan