Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping certain characters doesn't work

I'm sure this is a duplicate but I couldn't find the answer through search.

Here's my code

str_replace([' ',-,\(,\),\*,-,\|,\/], '', $params['telephone']), '0'

and that works. What I want it to be is:

str_replace([' ',-,\(,\),/,|,\*,-,\#,\], '', $params['telephone']), '0'

As soon as I add in # or \ it fails, and escaping them doesn't seem to work. Is there a different way to escape them?

And although it seemingly works, it does not seem to replace the initial space. Could that be the root of my problem?

like image 401
Eoin Avatar asked Nov 27 '25 23:11

Eoin


1 Answers

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.

like image 167
Wiktor Stribiżew Avatar answered Nov 29 '25 13:11

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!