0

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

jayjayh
  • 11
  • 2

3 Answers3

1

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

mega6382
  • 9,211
  • 17
  • 48
  • 69
0

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

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] 
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55