简体   繁体   English

PHP strpos和substr函数导致“允许的内存大小用尽”错误

[英]PHP strpos and substr functions causes 'Allowed memory size exhausted' error

The part of my code is the following: 我的代码部分如下:

while( $pos1 = stripos( $description, '<style' ) ) {
  $pos2 = stripos( $description, '</style>' ) + 8;
  $description = substr( $description, 0, $pos1 ).
                 substr( $description, $pos2 );     //   <= This string causing the error
}

Sometimes (not all the time!) I receiving the error: 有时(并非总是如此!),我收到错误消息:

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 107663188 bytes) in /path/to/my/script.php on line 88 致命错误:在第88行的/path/to/my/script.php中,耗尽了268435456字节的允许的内存大小(试图分配107663188字节)

88'th line indicated by the '<=' arrow above. 第88行由上方的“ <=”箭头指示。

The size of $description variable is about 100 kB's. $description变量的大小约为100 kB。 Besides I don't see any reason to believe that this code can cause accumulation of memory allocation without to be released. 此外,我看不出有任何理由相信此代码会导致内存分配的累积而不会被释放。

Do you see any flaws in my code? 您在我的代码中看到任何缺陷吗?

This code causes memory error 此代码导致内存错误

$description = 'hello<style></style>hello<style>';
while( $pos1 = stripos( $description, '<style' ) ) {
    $pos2 = stripos( $description, '</style>' ) + 8;
    $description = substr( $description, 0, $pos1 ).
        substr( $description, $pos2 );     //   <= This string causing the error
}

Looks like the problem caused by the fact that if </stile> is not find - the $description variable will grow up to infinity. 看起来好像是由于找不到</stile>导致的问题- $description变量将增长到无穷大。 This can appear if the <script> tag used in form <script ... /> Now the code is the following: 如果<script>标记以<script ... />形式使用,则可能会出现此代码,如下所示:

while( $pos1 = stripos( $description, '<style' ) ) {
  $pos2 = stripos( $description, '</style' ) + 8;
  if( $pos2 < $pos1 ) $pos2 = strpos( $description, '/>' ) + 2;
  if( $pos2 < $pos1 ) break 2;
  $description = substr( $description, 0, $pos1 ).
                 substr( $description, $pos2 );
}

Looks like there are no errors anymore... 看起来不再有错误...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM