Escaping characters by doubling them in PHP

我与影子孤独终老i 提交于 2019-12-13 10:21:16

问题


Is there a simple way to escape/unescape an arbitrary character in PHP by doubling it, for example:

  • in ANSI SQL, "you can ""escape"" this way"
  • in printf(), you can express a %% this way

Escaping is quite easy with str_replace(), but reversing the process to unescape the string is not that easy, so does anyone know of a pair of functions, or a library to do this?

The idea is that I need to serialize an array this way:

array('a','b', '~','c') => 'a~b~~~~c'

The individual strings cannot be empty.

Update: just realized that this "encoding" is broken, thanks to the useful comments below.


回答1:


Seems to me that

str_replace($char, $char.$char, $string);

and

str_replace($char.$char, $char, $string);

would be the complements of each other.




回答2:


As several users pointed it out in the comments, this question is flawed and has no possible answer.

A detailed explanation of my goal, and an appropriate answer have been provided at Provide a human-readable representation of an identifier?




回答3:


Take a look at addcslashes() and stripcslashes which will allow you to slash those characters you want to. That's maybe helpful.

Next to that your question does not really say where exactly you see a problem in unescaping, so I can not offer anything else than using the str_replace in reverse.




回答4:


Use preg_split() with

(?<!-)-(?!-)|(?:-)((?:-{2})+)(?:-)

You have to use the flag PREG_SPLIT_DELIM_CAPTURE. After some struggling, I am quite surprised that there actually is a regex solution for this.

a-b----c-hl--g------lo-x

becomes

Array ( [0] => a [1] => b [2] => -- [3] => c [4] => hl--g [5] => ---- [6] => lo [7] => x ) 


来源:https://stackoverflow.com/questions/6443607/escaping-characters-by-doubling-them-in-php

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