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

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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] 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.