删除脚本标记内的所有内容

时间:2014-01-25 23:43:17

标签: php

我有一个像

这样的字符串
$result = '
  stuff
  stuff
  <script>
    stuff I want to remove
  </script>
  morestuff
  morestuff
';

我想删除脚本标记和脚本标记本身之间的所有内容

我到目前为止

$result = preg_replace("/<script>.+?<\/script>/i", "", $result)

然而它无法正常工作

1 个答案:

答案 0 :(得分:1)

<?php

$string = 'Some valid and <script>some invalid</script> text!';
$out = delete_all_between('<script>', '</script>', $string);
print($out);

function delete_all_between($beginning, $end, $string) {
  $beginningPos = strpos($string, $beginning);
  $endPos = strpos($string, $end);
  if (!$beginningPos || !$endPos) {
    return $string;
  }

  $textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos);

  return str_replace($textToDelete, '', $string);
}
Source

Tim S