PHP preg_replace() - 内存问题。另类?

时间:2012-11-10 05:28:47

标签: php regex preg-replace slug

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

有没有其他方法可以完成像slug这样的字符串?

编辑:

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

有趣的是,原始的regex scrape,也使用了上面的slugify()函数,并且没有内存问题。但是,一旦我设置了DOMDocument刮擦,刮擦就会中途崩溃,错误始终在上面preg_replace()函数的slugify()行。

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

3 个答案:

答案 0 :(得分:3)

Preg_replace非常适合这个,但另一种方法是使用http://php.net/manual/en/function.str-replace.php

来破解它们

答案 1 :(得分:1)

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

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

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

答案 2 :(得分:0)

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

它对我有用。

相关问题