php分割函数preg_split()函数、用法、例子、参数说明

WBOY
Release: 2016-06-20 13:00:34
Original
1565 people have browsed it

php分割函数preg_split()函数、用法、例子、参数说明

preg_split

定义和用法

preg_split() 函数通过一个正则表达式分割字符串。

相关函数:spliti(),str_split(),explode(),implode(),chunk_split()

语法

preg_split(pattern,subject,limit,flags)
Copy after login
参数 描述
pattern 正则表达式
subject 待分割字符串
limit 限制分割得到的子串最多只有limit个
flags PREG_SPLIT_NO_EMPTY
如果这个标记被设置, preg_split() 将进返回分隔后的非空部分。
PREG_SPLIT_DELIM_CAPTURE
如果这个标记设置了,用于分隔的模式中的括号表达式将被捕获并返回。
PREG_SPLIT_OFFSET_CAPTURE
如果这个标记被设置, 对于每一个出现的匹配返回时将会附加字符串偏移量. 注意:这将会改变返回数组中的每一个元素, 使其每个元素成为一个由第0 个元素为分隔后的子串,第1个元素为该子串在subject 中的偏移量组成的数组。

例子

preg_split() 获取搜索字符串的部分

<?php //使用逗号或空格(包含" ", \r, \t, \n, \f)分隔短语
$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
print_r($keywords);
?>
Copy after login

输出:

 

Array
(
    [0] => hypertext
    [1] => language
    [2] => programming
)
Copy after login

将一个字符串分隔为组成它的字符

<?php $str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
?>
Copy after login

输出:

 

Array
(
    [0] => s
    [1] => t
    [2] => r
    [3] => i
    [4] => n
    [5] => g
)
Copy after login

分隔一个字符串并获取每部分的偏移量

<?php $str = 'hypertext language programming';
$chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
print_r($chars);
?>
Copy after login

输出:

Array
(
    [0] => Array
        (
            [0] => hypertext
            [1] => 0
        )
    [1] => Array
        (
            [0] => language
            [1] => 10
        )
    [2] => Array
        (
            [0] => programming
            [1] => 19
        )
)
Copy after login

 


Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!