正则表达式不剥离期

时间:2012-04-07 08:19:10

标签: php regex

为什么我的正则表达式没有剥离时期?最终结果应该只输出字母和数字字符,再加上' - ',但我一直在输出中得到句点。我试过修剪($ string,'。')但是没有用。请帮忙!

更新!我用正确的解决方案更新了代码。谢谢!

<?php
protected $trimCharacters = "/[^a-zA-Z0-9_-]/";
protected $validWords = "/[a-zA-Z0-9_-]+/";

private function cleanUpNoise($inputText){

  $this->inputText = preg_replace($this->trimCharacters, '', $this->inputText);
  $this->inputText = strtolower($this->inputText);
  $this->inputText = preg_match_all($this->validWords, $this->inputText, $matches);

  return $matches;
}
?>

1 个答案:

答案 0 :(得分:1)

你的正则表达式仅在你第一次模式匹配时获取...尝试在你的模式中设置全局标志,如

"/[\\s,\\+]+/g"

这样的东西
'/[\s,\+]+/g'
'/[^\w-]/g'

将是你的表达,你正在寻找...要注意:你必须逃避你的反斜杠......如果不是php将尝试解释\s \+ \w。 ..

一样使用它
protected $splitPattern = '/[\\s,\\+]+/g';
protected $trimCharacters = '/[^\\w-]/g';

编辑:

哦......你不能简化它:

$this->inputText = preg_replace($this->splitPattern, '', $this->inputText);
$this->inputText = preg_replace($this->trimCharacters, '', $this->inputText);