Im trying to get the content what is is the javascript script tag.
<script type="text/javascript"> [CONTENT HERE] </script>
currently i have something like this:
$start = preg_quote('<script type="text/javascript">', '/');
$end = preg_quote('</script>', '/');
preg_match('/ '.$start. '(.*?)' .$end.' /', $test, $matches);
But when i vardump it, its empty
Try the following instead:
$test = '<script type="text/javascript"> [CONTENT HERE] </script>';
$start = preg_quote('<script type="text/javascript">', '/');
$end = preg_quote('</script>', '/');
preg_match("/$start(.*?)$end/", $test, $matches);
var_dump($matches);
Output:
array (size=2)
0 => string '<script type="text/javascript"> [CONTENT HERE] </script>' (length=56)
1 => string ' [CONTENT HERE] ' (length=16)
The problem is actually the spaces after and before /
in the preg_match
Your regular expression requires there to be a space before the script start tag:
'/ '
The code works fine when I add that space to the data:
<?php
$test = ' <script type="text/javascript"> [CONTENT HERE] </script> ';
$matches = [];
$start = preg_quote('<script type="text/javascript">', '/');
$end = preg_quote('</script>', '/');
preg_match('/ '.$start. '(.*?)' .$end.' /', $test, $matches);
print_r($matches);
?>
Changing '/ '
to '/'
also works.
… but that said, you should avoid regular expressions when processing HTML and use a real parser instead.
An alternative approach would be to use strip_tags
instead...
$txt='<script type="text/javascript"> [CONTENT HERE] </script>';
echo strip_tags($txt);
Outputs
[CONTENT HERE]