问题
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);
}
回答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
来源:https://stackoverflow.com/questions/55177125/how-to-add-backslash-before-every-special-character-in-php