You want to remove a space, -
, (
, )
, *
, -
, |
, /
and also \
and #
symbols from the string.
You need to pass an array of these chars to str_replace
:
$arr = [ '-', '(', ')', '*', '-', '|', '/', '\\', '#'];
$result = str_replace($arr, '', $s);
Or, you may use a regex with preg_replace
like this:
$res = preg_replace('~[- ()*|/\\\\#]~', '', $s);
See the PHP demo.
Regex details:
~
is a regex delimiter, required by all preg_
functions
-
must be put at the start/end of the character class, or escaped if placed anywhere else, to match literal -
\
symbol must be matched with 2 literal \
s, and that means one needs 4 backslashes to match a single literal backslash
- Inside a character class,
*
, (
, )
, |
(and +
, ?
, .
, too) lose there special status and do not need to be escaped
- If you work with Unicode strings, add
u
modifier after the last ~
regex delimiter: '~[- ()*|/\\\\#]~u'
.
The difference between string replace and preg replace
str_replace
replaces a specific occurrence of a literal string, for instance foo
will only match and replace that: foo
.
preg_replace
will perform replacements using a regular expression, for instance /f.{2}/
will match and replace foo
, but also fey
, fir
, fox
, f12
, f )
etc.