-2

I want to add backslash before every character in php

below is my string

AT POST :- SARIGAM, (BHANDARI STREET)
PIN : 396155 STATE: GUJARAT 
VALSAD GUJARAT   396155 
India

Some special character are not i this string but answer should be valid for all the special character.

I have tried below, but not able to success.

if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $address))
            {               
                str_replace('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', "\\", $address);
            }
LOKESH
  • 1,303
  • 1
  • 16
  • 29

1 Answers1

1

You can just use preg_replace to replace all non-alphanumeric and whitespace characters with a backslash and the character:

echo preg_replace('/([^A-Za-z0-9\s])/', '\\\\$1', $address);

Output:

AT POST \:\- SARIGAM\, \(BHANDARI STREET\)
PIN \: 396155 STATE\: GUJARAT 
VALSAD GUJARAT 396155 
India

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95