Home  >  Article  >  Backend Development  >  PHP uses preg_split() to split special characters

PHP uses preg_split() to split special characters

墨辰丷
墨辰丷Original
2018-05-26 11:06:081733browse

这篇文章主要介绍了PHP使用preg_split()分割特殊字符(元字符等)的方法,结合具体实例形式分析了php正则分割的操作技巧与注意事项,需要的朋友可以参考下

具体如下:

这里所说的特殊字符就是正则中使用的特殊字符,如: | . + 等

其它的先不说,来个实例:

$pattern="/[,-\\|\\.]/";
$subject="aaa,bbb,ccc-ddd-eee-fff|ggg|hhh.iii.jjj.kkk";
$spr=preg_split($pattern, $subject);
print_r($spr);

结果:

Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => [7] => [8] => [9] => [10] => [11] => [12] => [13] => [14] => [15] => [16] => [17] => [18] => [19] => [20] => [21] => [22] => [23] => [24] => [25] => [26] => [27] => [28] => [29] => [30] => [31] => [32] => [33] => [34] => [35] => [36] => [37] => [38] => [39] => [40] => [41] => [42] => [43] => )

很显然,这不是我们想要的结果,郁闷了好一会,才找到是什么原因:

把正则表达式内的特殊字符放到前面就没事了, 也就是

$pattern="/[\\|\\.,-]/";

结果:

Array ( [0] => aaa [1] => bbb [2] => ccc [3] => ddd [4] => eee [5] => fff [6] => ggg [7] => hhh [8] => iii [9] => jjj [10] => kkk )

好了,这就是我们要的结果了

总结:当使用正则表达式中的元字符,普通字符进行 [ ]内的多个字符分割的时候,要把待转义的元字符放在前面.

以上就是本文的全部内容,希望对大家的学习有所帮助。


相关推荐:

PHP使用preg_split和explode实现分割textarea存放内容的方法

code spliting优化Vue打包步骤详解

PyQt5每天必学之QSplitter实现窗口分隔

The above is the detailed content of PHP uses preg_split() to split special characters. 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