【问题标题】:PHP preg_replace() - Memory Issues. Alternative?PHP preg_replace() - 内存问题。选择?
【发布时间】:2012-10-30 10:48:58
【问题描述】:

在我正在开发的网站中,我使用this question 中的答案将字符串转换为 slug。它有效,但我发现存在巨大的内存泄漏问题。我做了一些研究,发现这只是目前 PHP 中的一个错误。

有没有其他方法可以完成诸如字符串之类的事情?

编辑:

这个问题还有另一个有趣的角度。我正在重新开发一个使用 regex 制作的爬虫(呃,我知道),所以我决定使用 DOMDocument / XPath 作为解决方案。

有趣的是,原来的regexscrape,也使用了上面的slugify()函数,而且没有内存问题。但是,一旦我设置了 DOMDocument 抓取,抓取在中途崩溃,并且错误始终出现在上面slugify() 函数中的preg_replace() 行。

因此,尽管这两种情况都使用完全相同的 slugify() 函数,但只有 DOMDocument 版本在 preg_replace() 行上崩溃

【问题讨论】:

    标签: php regex preg-replace slug


    【解决方案1】:

    Preg_replace 对此非常有用,但另一种方法是使用 http://php.net/manual/en/function.str-replace.php 破解它们

    【讨论】:

    • 正确。任何指向使用此功能的 slugify() 函数的指针?
    • 哈,是的,我知道...但是我正在刮擦(不使用 preg_replace!使用 DOM 文档)但是当某个文本进入时,我必须在进入之前将其变成一个 slug数据库。所以我最终得到了这些 preg_replace() 循环,显然它每次都在增加内存使用量
    • 哎呀!我不知道的人。我仍然没有为您提供强有力的解决方案:/您是否尝试过将 preg_replace 分离到一个函数中以查看是否可以杀死它?也许可以尝试一些 phpUnit ......对不起,伙计 :(
    • 嗯,我还没有尝试将 preg_replace() 放在单独的函数中。 “杀了它”是什么意思?你有例子吗?
    【解决方案2】:

    通过取消设置变量,您应该能够释放一些内存。是的,它很脏,但可能有用

    static public function slugify($text) {    
      // replace non letter or digits by -   
      $text2 = preg_replace('~[^\\pL\d]+~u', '-', $text);
    
      // unset $text to free up space
      unset($text);
      // trim   
      $text2 = trim($text2, '-');
    
      // transliterate   
      $text2 = iconv('utf-8', 'us-ascii//TRANSLIT', $text2);
    
      // lowercase
      $text2 = strtolower($text2);
    
      // remove unwanted characters
      $text = preg_replace('~[^-\w]+~', '', $text2);
    
      // unset $text2 to free up space
      unset($text2);
    
      if (empty($text))   {
        return 'n-a';   
      }
      return $text; 
    }
    

    https://bugs.php.net/bug.php?id=35258&edit=1

    http://www.php.net/manual/en/function.preg-replace.php#84285

    希望您能找到更清洁的解决方案。

    【讨论】:

    • 不幸的是,这似乎没有帮助
    【解决方案3】:

    我发现了这个错误 https://bugs.php.net/bug.php?id=38728,它说要使用 mb_eregi_replace() 函数 insead。

    它对我有用。

    【讨论】:

      猜你喜欢
      • 2011-08-24
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 2011-03-09
      • 2018-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多