Home  >  Article  >  Backend Development  >  preg_split and explode implement splitting textarea to store content code

preg_split and explode implement splitting textarea to store content code

小云云
小云云Original
2018-02-10 10:33:081214browse

There is an urgent bug today. It is said that after the whitelist is configured in the background, it is invalid in the mobile app and the content is still displayed. After receiving the email, I went through the process and found that the background configuration whitelist was configured in the textarea, one per line. Looking at the code again, I found that the explode function was used to separate it, and the separator was \r\n. This article mainly shares with you how PHP uses preg_split and explode to split textarea to store content, and analyzes the functions and usage techniques of preg_split and explode functions in the form of examples, as well as relevant precautions in the text string splitting process.

The code is roughly as follows


explode('\r\n', $val);

After that, I tested it on my development machine and found that this would not split the content of the textarea stored in the database at all. , so I searched in the manual and found a very useful function preg_split


$str = '1
2
3
4
5';
print_r(preg_split("/\n/",$str));
/*
Array
(
  [0] => 1
  [1] => 2
  [2] => 3
  [3] => 4
  [4] => 5
)
*/

[update]

In the afternoon, I was reminded by a colleague and found that it turned out to be There is a problem with the separator, because in Chrome and Firefox browsers, textarea has a newline character of \n, while in IE it has a newline character of \r\n, so I used str_replace to replace it


$str = '1
2
3
4
5';
print_r(explode("\n", str_replace("\r\n", "\n", $str)));
Array
(
  [0] => 1
  [1] => 2
  [2] => 3
  [3] => 4
  [4] => 5
)

Related recommendations:

PHP uses preg_split() to split special characters (metacharacters, etc.) analysis

(PHP) Regular expression-Usage of preg_split function

Correct use of PHP function preg_split_PHP tutorial

The above is the detailed content of preg_split and explode implement splitting textarea to store content code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn