简体   繁体   中英

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. 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 ...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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