服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - PHP教程 - php字符串的替换,分割和连接方法

php字符串的替换,分割和连接方法

2021-01-22 16:14紫云的博客 PHP教程

这篇文章主要介绍了php字符串的替换,分割和连接方法,分析了preg_replace、str_replace、preg_split、explode及implode等函数的功能与使用方法,需要的朋友可以参考下

本文实例讲述了php字符串的替换,分割和连接方法。分享给大家供大家参考,具体如下:

字符串的替换

1. 执行一个正则表达式的搜索和替换

复制代码 代码如下:
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

 

搜索subject中匹配pattern的部分, 以replacement进行替换.

2. 子字符串替换

复制代码 代码如下:
mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )


该函数返回一个字符串或者数组。该字符串或数组是将 subject 中全部的 search 都被 replace 替换之后的结果。

 

字符串的分割和连接

通过一个正则表达式分隔字符串

说明

1. array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )

通过一个正则表达式分隔给定字符串.

2. explode — 使用一个字符串分割另一个字符串

说明:

array explode ( string $separator , string $string [, int $limit ] )

?
1
2
3
4
5
$str = 'one|two|three|four';
// 正数的 limit
print_r(explode('|', $str, 2));
// 负数的 limit(自 PHP 5.1 起)
print_r(explode('|', $str, -1));

以上例程会输出:

?
1
2
3
4
5
6
7
8
9
10
11
Array
(
  [0] => one
  [1] => two|three|four
)
Array
(
  [0] => one
  [1] => two
  [2] => three
)

3. string implode(string glue, array pieces) ———— 连接数组称为字符串

?
1
2
$lan=array("a","b","c");
implode("+", $lan);//a+b+c

希望本文所述对大家PHP程序设计有所帮助。

延伸 · 阅读

精彩推荐