Preg_replace regex issue

I am trying to clear a string.

I need to allow only

  • Upper / lower letters
  • the numbers
  • spaces, tabs, carriage returns
  • these characters: _-+*()[]!#?.,;:'"<>

Everything else must go bye. How should I do it? I have this one that works for letters, numbers and upper / lower case spaces. But I do not know how to account for tabs, carriage returns, or how to perform special characters?

$str = preg_replace('/[^a-z0-9 ]/i', '', $str);
+3
source share
3 answers

Try

$str = preg_replace('/[^\w\r\n\t+*()[\]!#?.\,;:\'"<> -]/', '', $str);
+2
source

\ s - space character (includes tabs and line breaks)
\ r - carriage return
Use the "\" character for special symobls.

+1
source

$str = 'sample|';
$result = !(bool)strlen(preg_replace('/^[a-z0-9A-Z\r\s:_-+*()[]!#?.,;:\>\<]*/', '', $str))

+1

Source: https://habr.com/ru/post/1791650/


All Articles