I am trying to add a back slash to a string having special character.
My input is:
db:xz~sf!fkd@djf#dfs$dlf%dks^kd&fkf*kdf(dls)kls-fls+fsd=slf_fls[fdf]fdf{ffl}sl|dkf\fsl'skfj
And my output should be:
db\:xz\~sf\!fkd\@djf\#dfs\$dlf\%dks\^kd\&fkf\*kdf\(dls\)kls\-fls\+fsd\=slf\_fls\[fdf\]fdf\{ffl\}sl\|dkf\\fsl\'skfj
And I have the following piece of code which is only replacing the special character with the back slash character:
<?php
echo $string = "db:xz~sf!fkd@djf#dfs$dlf%dks^kd&fkf*kdf(dls)kls-fls+fsd=slf_fls[fdf]fdf{ffl}sl|dkf\fsl'skfj";
echo preg_replace('/[^A-Za-z0-9\-]/', '\\', $string);
So could someone help me regarding this?
You can use:
$s = 'db:xz~sf!fkd@djf#dfs$dlf%dks^kd&fkf*kdf(dls)kls-fls+fsd=slf_fls[fdf]fdf{ffl}sl|dkf\fsl\'skfj';
echo preg_replace('/\W/', '\\\\$0', $s)
//=> db\:xz\~sf\!fkd\@djf\#dfs\$dlf\%dks\^kd\&fkf\*kdf\(dls\)kls\-fls\+fsd\=slf_fls\[fdf\]fdf\{ffl\}sl\|dkf\\fsl\'skfj
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.