i am trying to add code before and after inside the script tag with PHP
<script>
hbspt.forms.create({
region: "na1",
portalId: "",
formId: ""
});
</script>
I am trying preg_grep with preg_replace to achieve it but i can not able to use multiple variable inside preg_replace and if i use array it is just output array.
$result = preg_grep("/hbspt\s*([\s\S]*?);/", $matches);
$before = 'before';
$after = 'after';
$final = $before = $after;
$regexes = '/hbspt\s*([\s\S]*?);/';
return preg_replace( $regexes, "before $result after", $buffer );
where i am making mistake?
The result i want
<script>
before
hbspt.forms.create({
region: "na1",
portalId: "",
formId: ""
});
after
</script>
CodePudding user response:
The easiest way to achieve what you want is:
$before = 'before';
$after = 'after';
$source = '<script>
hbspt.forms.create({
region: "na1",
portalId: "",
formId: ""
});
</script>';
echo "<script>\n$before\n" .
strip_tags($source) .
"\n$after\n</script>";
This results in:
<script>
before
hbspt.forms.create({
region: "na1",
portalId: "",
formId: ""
});
after
</script>
See a PHP fiddle and strip_tags().
Alternatively, but slightly more complex, would be:
echo "<script>\n$before\n" .
substr($source, 8, -9) .
"\n$after\n</script>";
See: PHP Fiddle and substr().
The advantage is that it won't remove any tags inside your javascript.