2012-04-07 77 views
0

为什么我的正则表达式没有剥离期间?最终结果应该只输出字母和数字字符,再加上' - ',但我不断在输出中获取句点。我试过trim($ 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; 
} 
?> 
+0

将删除所有非字母数字或 - 字符隐删除空白字符,冒号和+?因此,删除与你的'$ splitPattern'匹配的所有内容都会让你的下一步变得不那么重要,你的'$ trimCharacters'暗示'$ splitPattern'? – Kerwindena 2012-04-07 09:17:41

+0

implicts是什么意思? – Wes 2012-04-08 03:27:58

+0

你是对的,但即使删除了$ splitPattern,我的正则表达式仍然在释放。“通过。如果我在regexpal.com上测试它,它说它应该可以工作 – Wes 2012-04-08 03:47:25

回答

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); 
+0

这个全局修饰符在php中是如何识别的? – Wes 2012-04-08 03:23:46

+0

哦,对不起,你可以忽略g-flag当然,因为: “限制: 每个主题字符串中每种模式的最大可能替代数。默认为-1(无限制)。“ – Kerwindena 2012-04-08 08:16:32