简体   繁体   English

正则表达式不剥离句点

[英]Regex not stripping periods

Why is my regex not stripping out the periods?为什么我的正则表达式没有去掉句点? The end result should output only alpha and numeric characters, plus '-'s, but I keep getting periods in the output. I've tried trim($string, '.') but didn't work.最终结果应该是 output 只有字母和数字字符,加上“-”,但我一直在 output 中得到句点。我试过 trim($string, '.') 但没有用。 Help Please!请帮助!

Update.更新。 I've updated the code with the correct solution.我已经用正确的解决方案更新了代码。 Thanks!谢谢!

<?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;
}
?>

Your regex only fetches the first time you pattern matches... try setting the global flag in you pattern like您的正则表达式仅在您第一次进行模式匹配时获取...尝试在您的模式中设置全局标志,例如

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

Something like就像是

'/[\s,\+]+/g'
'/[^\w-]/g'

would be your expressions, you are looking for... be aware: you have to escape your backslashes... if not php will try to interpret \s \+ \w ...将是你的表达,你正在寻找......注意:你必须转义你的反斜杠......如果不是 php 将尝试解释\s \+ \w ...

use it like像使用它

protected $splitPattern = '/[\\s,\\+]+/g';
protected $trimCharacters = '/[^\\w-]/g';

Edit:编辑:

Ohh... cant you simplify it to:哦...您不能将其简化为:

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

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

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