How to add backslash before every special character in php

℡╲_俬逩灬. 提交于 2021-01-20 14:00:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!