Home > Article > Backend Development > Summary of frequently asked questions about PHP string operations
The examples in this article describe common problems with PHP string operations. I share it with you for your reference. The details are as follows:
I remember a saying that I heard when I was learning PHP and thought it was very cool: all programs are strings. The so-called programming is just to let data flow between various code pages like water. flow away. In my current work, I have indeed found that data format is a difficult problem, involving the assembly, splitting and reassembly of data.
The reason why I mention Json is because when using ajax, it often involves data interaction between the program and Js. Since JS does not recognize arrays in PHP, PHP does not recognize arrays or objects in JS. At this time, the free format of Json can solve this problem very well.
Its format is as follows:
For example:
{"username": "Eric","age":23,"sex": "man"}
Our powerful PHP has provided built-in functions for this: json_encode() and json_decode().
It’s easy to understand, json_encode() converts a PHP array into Json. On the contrary, json_decode() converts Json into a PHP array.
For example:
$array = array("name" => "Eric","age" => 23); echo json_encode($array);
The program will print out
{"name":"Eric","age":23}
$array = array(0 => "Eric", 1 => 23); echo json_encode($array);
The program will print out:
["Eric",23]
Except for this relatively free format, The more common one is string Interchange and splicing with arrays:
1. Convert strings into arrays:
explode(separate,string)
Example:
$str = "Hello world It's a beautiful day"; explode(" ",$str);//以空格为分界点
Return:
array([0]=>"Hello",[1]=>"world",[2]=>"It's",[3]=>"a",[4]=>"beautiful",[5]=>"day")
will The serialized string is returned to its original array form.
2. Convert the array into a string:
implode(separate,array) //The reverse operation of explode, separate defaults to the empty character
Example:
$array = ('hello','world','!'); implode(" ",$array);
Return:
"hello world !"
Hope this article The above will be helpful to everyone in PHP programming.
For more articles related to summaries of frequently asked questions about PHP string operations, please pay attention to the PHP Chinese website!