Escaping certain characters doesn't work

I'm sure this is a duplicate, but I could not find an answer through a search.

Here's my code

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

and it works. I want this to be:

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

As soon as I add in #

or \

, it fails and running away from them doesn't seem to work. Is there any other way to avoid them?

And while it seems to work, it doesn't seem to replace the initial space. Could this be the cause of my problem?

+3


source to share


3 answers


Do you want to remove the spaces, -

, (

, )

, *

, -

, |

, /

, and \

and #

characters from a string.

You need to pass an array of these characters to str_replace

:

$arr = [ '-', '(', ')', '*', '-', '|', '/', '\\', '#'];
$result = str_replace($arr, '', $s);

      

Or you can use a regular expression with the preg_replace

following:

$res = preg_replace('~[- ()*|/\\\\#]~', '', $s);

      

See PHP demo .



Regular Expression Details :

  • ~

    is the regex delimiter required by all functions preg_

  • -

    must be placed at the beginning / end of the character class, or escaped if placed elsewhere, to match the literal -

    Character
  • \

    has to be matched against 2 \

    s, which means you need 4 backslashes to match a single backslash
  • Inside a character class *

    , (

    , )

    , |

    (and +

    , ?

    , .

    too) lose their special status and there is no need to be shielded
  • If you work with Unicode strings, add a modifier u

    after the last separator regular expression ~

    : '~[- ()*|/\\\\#]~u'

    .

Difference between string replacement and preg replacement

str_replace

replaces certain occurrence of a literal string, such as foo

will fit and replace it with: foo

.

preg_replace

will carry out the replacement using a regular expression, for example, /f.{2}/

will match and replace foo

, but also fey

, fir

, fox

, f12

, f )

, etc.

+3


source


Use preg_replace ()!

You can remove certain characters this way

$foo = preg_replace('/[yourcharacters]/', '', $foo);

      



And you can also do it the other way (removing everything but certain characters) by adding a ^ (see regex tables).

$foo = preg_replace('/[^theonlyallowedcharacters]/', '', $foo);

      

+2


source


I think you need to add \ for special characters to your regex.

Please replace this code

 ['',\(,\),\/,\|,\*,-,\#,\\]

      

Instead of yours,

[' ',-,\(,\),/,|,\*,-,\#,\]

      

Hope this helps.

0


source







All Articles