Table of Contents
字符串格式化
1,去空格:trim(),ltrim(),rtrim()
2,格式化字符串:printf(),sprintf()
3,改变字符串中的字符大小写
a).将字符转换为大写:strtoupper()
b).将字符转换为小写 :strtolower()
c).如果第一个字符是字母,就转换成大写:ucfirst()
d).将字符串中每个单词的第一个字母转成大写:ucwords()
4,转义字符串
5,编码字符串
用字符串函数连接和分隔字符串
1,分隔字符串:explode()
2,截取字符串:substr()
字符串比较
1,字符串排序:strcmp(),strcasecmp(),strnatcmp()
2,获得字符串的长度:strlen()
使用字符串函数匹配和替换子字符串
1,在字符串中查找字符串:strstr(),strchr(),strrchr()和strissr()
2,查找字符串的位置:strpos(),strrpos()
3,替换子字符串:str_replace(),substr_replace()
使用正则表达式
1,查找子字符串:ereg(),eregi()
2,替换子字符串:ereg_replace(),eregi_replace()
3,分隔字符串:split()
Home php教程 php手册 PHP学习:字符串操作和正则表达式

PHP学习:字符串操作和正则表达式

Jun 14, 2016 am 12:02 AM
php learning code string Open source regular expression programming programming language software development

主要内容:

  1. 字符串格式化;
  2. 用字符串函数连接和分隔字符串;
  3. 字符串比较;
  4. 使用字符串函数匹配和替换子字符串;
  5. 使用正则表达式;

字符串格式化

1,去空格:trim(),ltrim(),rtrim()

trim()函数去掉头尾两边的空格。

ltrim()函数去掉开始的空格。

rtrim()函数去掉结尾的空格。

2,格式化字符串:printf(),sprintf()

printf()函数和sprintf()函数,和echo的功能相同,都会打印字符串。但是它们可以实现更复杂的格式(象C#中string.Format()类似)。

printf()和sprintf()原型如下:

string sprintf(string format[,mixed args..]);
void printf(string format[,mixed args...]);
Copy after login

sprintf()返回格式化后的字符串。而printf直接将结果输出。它们两个的功能类似,所以就已printf()为例。

$boy = "boy";
echo "i am a $boy";
echo '<br />';
printf("i am a %s",$boy);
Copy after login

上面输出的结果一样。

其中format中的类型可以有以下几种:

string-format-type

format中的所有转换类型都以%开始。如果想打印一个“%”符号,必须使用两个“%%”

3,改变字符串中的字符大小写

a).将字符转换为大写:strtoupper()

$str = "i am a boy";
echo strtoupper($str);
Copy after login

b).将字符转换为小写 :strtolower()

$str = "I Am A Boy";
echo strtolower($str);
Copy after login

c).如果第一个字符是字母,就转换成大写:ucfirst()

$str = "i am a boy";
echo ucfirst($str);
Copy after login

d).将字符串中每个单词的第一个字母转成大写:ucwords()

$str = "i am a boy";
echo ucwords($str);
Copy after login

4,转义字符串

addslashes()函数就是把“转换成\”,或者把\转成双斜杠\\等等之类的操作。

$str = '"i am a [\] boy."';
echo addslashes($str);
Copy after login

输出:\"i am a [\\] boy.\"

addslashes()函数相反的函数就是stripslashes()。

5,编码字符串

htmlspecialchars()函数把&,<,>,“等等,编码成浏览器不能解释的字符。

用字符串函数连接和分隔字符串

1,分隔字符串:explode()

它的原型如下:

array explode(string separator,string input[,int limit]);
Copy after login

可以看出返回数组。使用如下:

$str = "1,2,3,4,5";
$arr = explode(',',$str);
foreach($arr as $v){
	echo $v.'<br />';
}
Copy after login

返回1 2 3 4 5

既然有分隔就会有整合。不错,implode()和join()函数实现就是和explode()相反的操作。

$str = "1,2,3,4,5";
$arr = explode(',',$str);
echo implode(',',$arr);
Copy after login

2,截取字符串:substr()

substr()函数的原型如下:

string substr(string input,int start[,int length]);
Copy after login

第二个参数表示截取的开始位置。

第三个参数表示截取的长度。

使用如下:

$str = "i am a boy";
echo substr($str,2);
Copy after login

输出:am a boy

需要注意的是,第二个参数和第三个参数可以为负,如果为负,就意味着从后边开始。

function reverse_i($str){
		for($i=1;$i<=strlen($str);$i++){
			echo substr($str,-$i,1);
		}
		return;
	}
	reverse_i('word');
Copy after login

返回:drow;

字符串比较

1,字符串排序:strcmp(),strcasecmp(),strnatcmp()

strcmp()的原型如下:

int strcmp(string str1,string str2);
Copy after login

如果两个字符串相等,返回0;如果按字典顺序str1在str2后面就返回一个正数,反之。这个函数是区分大小写的。

$str1 = "2";
$str2 = "12";
echo strcmp($str1,$str2);
Copy after login

返回1,说明它是按字典顺序排列的,$str1的第一个字符大于$str2的第一个字符。

strcasecmp()函数除了不区分大小写之外,其他和strcmp()函数一样。

而strnatcmp()则是按照人们习惯的顺序进行排序。它也不区分大小写。

$str1 = "2";
$str2 = "12";
echo strnatcmp($str1,$str2);
Copy after login

返回-1,说明12比2大。

2,获得字符串的长度:strlen()

strlen(“hello”),输出结果为5。

使用字符串函数匹配和替换子字符串

1,在字符串中查找字符串:strstr(),strchr(),strrchr()和strissr()

这些函数看起来张得差不多,真是难记啊!~~

最常用的是strstr()函数,strchr()函数和strstr()函数时一样的,虽然感觉strchr()是查找一个字符的意思。

strstr()函数的原型如下:

string strstr(string haystack,string needle);
Copy after login
第一个参数为整个字符串。
Copy after login

第二个参数为需要查找的子字符串。

如果找到一个匹配,函数会从needle前面返回haystack,否则返回false。如果存在不止一个needle,返回的字符串从出现第一个needle的位置开始。

a).一个精确匹配

$str1 = "To all, I am very sad to tell you that I’ve just been fired.It has been my pleasure to work with all of you and I wish you only the best going forward.";
echo strstr($str1,'very');
Copy after login

输出:very sad to tell you that I’ve just been fired.It has been my pleasure to work with all of you and I wish you only the best going forward.

b).多个匹配

$str1 = "To all, I am very sad to tell you that I’ve just been fired.It has been my pleasure to work with all of you and I wish you only the best going forward";
echo strstr($str1,'been');
Copy after login

输出:been fired.It has been my pleasure to work with all of you and I wish you only the best going forward.

函数strstr()有两个变体。第一个是stristr()函数,它几乎和strstr()函数一样,但区别就是不区分大小写。

第二个是strrchr()函数,它几乎和strstr()一样,但会从最后出现needle的位置的前面返回字符串haystack。

此函数第二个参数为字符。

$str1 = "To all, I am very sad to tell you that I’ve just been fired.It has been my pleasure to work with all of you and I wish you only the best going forward.";
echo strrchr($str1,'w');
Copy after login
输出:ward.

2,查找字符串的位置:strpos(),strrpos()

strpos()函数和strstr()函数的操作类似。但它不是返回一个字符串,而是返回子字符串在整个字符串中的位置。我们平常使用的也是这个。而且比strstr()速度也快。

strpos()函数原型如下:

int strpos(string haystack,string needle,int offset);
Copy after login

第三个参数是可选的,标示开始搜索的位置。

$str1 = "hello word";
echo strpos($str1,'o');
Copy after login

输出:4,位置是从0开始起。也可以用子字符串,这里只是出于演示目的。

$str1 = "hello word";
echo strpos($str1,'o',5);
Copy after login

输出:7。是从位置5开始搜索,也就看不到位置4的那个“o”了。

函数strrpos()也几乎一样,但返回的是子字符串在整个字符串中最后一次出现的位置。

$str1 = "hello word";
echo strrpos($str1,'o');
Copy after login

输出:7。说明“o”在hello word中最后一个位置的7。

这里需要注意一下,PHP中的false等于0,如果strpos()或者strrpos()都返回false(没有找到)或者在第一个字符就找到了(第一个字符的起始位置是0),

那么就区分不出来是找到,还是未找到了。那怎么办呢?只能用“===”恒等式来避免这个问题了。

$str1 = "hello word";
$position = strrpos($str1,'h'); //第一个字符就找到了,$position ==0
if($position === false){
	echo '没有找到';
}else{
	echo $position;
}
Copy after login

3,替换子字符串:str_replace(),substr_replace()

str_replace()函数的原型如下:

mixed str_replace(mixed needle,mixed new_needle,mixed haystack[,int &count]);
Copy after login

第三个参数是可选的。它包含了要执行的替换操作次数。

返回替换过的字符串。

$str1 = "hello word";
echo str_replace('word','china',$str1);
Copy after login

输出:hello china

函数substr_replace()则用来在给定位置中查找和替换字符串中特定的子字符串。原型如下:

string substr_replace(string string,string replacement,int start[,int length]);
Copy after login

这个函数使用字符串replacement替换整个字符串string中的一部分。具体是那一部分则取决于起始位置和可选参数length的值。

需要注意的是,start的值如果是0或者一个正值,就是从字符串开始计算偏移量;如果是一个负值,就从字符串末尾开始的一个偏移量。

使用正则表达式

1,查找子字符串:ereg(),eregi()

ereg()函数的原型如下:

int ereg(string pattern,string search,array [matches]);
Copy after login

在search字符串中查找正则为pattern的表达式,如果发现了与pattern的字表达式相匹配的字符串,这些字符串将会存储在数组matches中,每个数组元素对应一个子表达式。

函数eregi()函数除了不区分大小写外,其功能与ereg()一样。

$str1 = "xxx@gmail.com.cn";
if(!eregi('[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}',$str1)){
	echo '不是正确的Email';
}else{
	echo '正确';
}
Copy after login

2,替换子字符串:ereg_replace(),eregi_replace()

于str_replace()函数一样,只不过这两个使用正则表达式当做参数。

ereg_replace()的原型如下:

string ereg_replace(string pattern,string replacement,string search);
Copy after login
$str1 = "123123@gmail.com.cn";
echo ereg_replace('[A-Z0-9._%+-]+@','**@',$str1);
Copy after login

输出:**@gmail.com.cn

函数eregi_replace除了不区分大小写外,其他与ereg_replace()相同。

3,分隔字符串:split()

函数split()的原型如下:

array split(string pattern,string search[,int max]);
Copy after login

第三个参数为可选,表示进入数组中的元素个数。

返回值是数组。

$str1 = "123123@gmail.com.cn";
$arr = split('\.|@',$str1);
while(list($key,$value) = each($arr)){
	echo '<br />'.$key.'--'.$value;
}
Copy after login

输出:

0--123123
1--gmail
2--com
3--cn

split()函数和explode()函数有点相似,前者是用正则表达式当做分隔符,后者是用字符串当做分隔符。

参考:PHP与MySQL.WEB开发

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Huawei's official introductory tutorial for Cangjie programming language is released. Learn how to obtain the universal version SDK in one article Huawei's official introductory tutorial for Cangjie programming language is released. Learn how to obtain the universal version SDK in one article Jun 25, 2024 am 08:05 AM

According to news from this site on June 24, at the keynote speech of the HDC2024 Huawei Developer Conference on June 21, Gong Ti, President of Huawei Terminal BG Software Department, officially announced Huawei’s self-developed Cangjie programming language. This language has been developed for 5 years and is now available for developer preview. Huawei's official developer website has now launched the official introductory tutorial video of Cangjie programming language to facilitate developers to get started and understand it. This tutorial will take users to experience Cangjie, learn Cangjie, and apply Cangjie, including using Cangjie language to estimate pi, calculate the stem and branch rules for each month of 2024, see N ways of expressing binary trees in Cangjie language, and use enumeration types to implement Algebraic calculations, signal system simulation using interfaces and extensions, and new syntax using Cangjie macros, etc. This site has tutorial access address: ht

After 5 years of research and development, Huawei's next-generation programming language 'Cangjie” has officially launched its preview After 5 years of research and development, Huawei's next-generation programming language 'Cangjie” has officially launched its preview Jun 22, 2024 am 09:54 AM

This site reported on June 21 that at the HDC2024 Huawei Developer Conference this afternoon, Gong Ti, President of Huawei Terminal BG Software Department, officially announced Huawei’s self-developed Cangjie programming language and released a developer preview version of HarmonyOSNEXT Cangjie language. This is the first time Huawei has publicly released the Cangjie programming language. Gong Ti said: "In 2019, the Cangjie programming language project was born at Huawei. After 5 years of R&D accumulation and heavy R&D investment, it finally meets global developers today. Cangjie programming language integrates modern language features, comprehensive compilation optimization and Runtime implementation and out-of-the-box IDE tool chain support create a friendly development experience and excellent program performance for developers. "According to reports, Cangjie programming language is an all-scenario intelligence tool.

Huawei launches HarmonyOS NEXT Cangjie programming language developer preview beta recruitment Huawei launches HarmonyOS NEXT Cangjie programming language developer preview beta recruitment Jun 22, 2024 am 04:07 AM

According to news from this site on June 21, Huawei’s self-developed Cangjie programming language was officially unveiled today, and the official announced the launch of HarmonyOSNEXT Cangjie language developer preview version Beta recruitment. This upgrade is an early adopter upgrade to the developer preview version, which provides Cangjie language SDK, developer guides and related DevEcoStudio plug-ins for developers to use Cangjie language to develop, debug and run HarmonyOSNext applications. Registration period: June 21, 2024 - October 21, 2024 Application requirements: This HarmonyOSNEXT Cangjie Language Developer Preview Beta recruitment event is only open to the following developers: 1) Real names have been completed in the Huawei Developer Alliance Certification; 2) Complete H

Tianjin University and Beihang University are deeply involved in Huawei's 'Cangjie” project and launched the first AI agent programming framework 'Cangqiong” based on domestic programming languages. Tianjin University and Beihang University are deeply involved in Huawei's 'Cangjie” project and launched the first AI agent programming framework 'Cangqiong” based on domestic programming languages. Jun 23, 2024 am 08:37 AM

According to news from this site on June 22, Huawei yesterday introduced Huawei’s self-developed programming language-Cangjie to developers around the world. This is the first public appearance of Cangjie programming language. According to inquiries on this site, Tianjin University and Beijing University of Aeronautics and Astronautics were deeply involved in the research and development of Huawei’s “Cangjie”. Tianjin University: Cangjie Programming Language Compiler The software engineering team of the Department of Intelligence and Computing of Tianjin University joined hands with the Huawei Cangjie team to deeply participate in the quality assurance research of the Cangjie programming language compiler. According to reports, the Cangjie compiler is the basic software that is symbiotic with the Cangjie programming language. In the preparatory stage of the Cangjie programming language, a high-quality compiler that matches it became one of the core goals. As the Cangjie programming language evolves, the Cangjie compiler is constantly being upgraded and improved. In the past five years, Tianjin University

Huawei's self-developed Cangjie programming language official website and development documents are online, integrating into the Hongmeng ecosystem for the first time Huawei's self-developed Cangjie programming language official website and development documents are online, integrating into the Hongmeng ecosystem for the first time Jun 22, 2024 am 03:10 AM

According to news from this site on June 21, before the HDC2024 Huawei Developer Conference, Huawei’s self-developed Cangjie programming language was officially unveiled, and the Cangjie official website is now online. The official website introduction shows that Cangjie programming language is a new generation programming language for all-scenario intelligence, focusing on "native intelligence, natural all-scenarios, high performance, and strong security." Integrate into the Hongmeng ecosystem to provide developers with a good programming experience. The official website attached to this site introduces as follows: Native intelligent programming framework embedded with AgentDSL, organic integration of natural language & programming language; multi-Agent collaboration, simplified symbolic expression, free combination of patterns, supporting the development of various intelligent applications. Innately lightweight and scalable runtime for all scenes, modular layered design, no matter how small the memory is, it can be accommodated; all-scenario domain expansion

The last link of Huawei's pure-blood Hongmeng ecosystem! Self-developed Cangjie programming language will make its debut The last link of Huawei's pure-blood Hongmeng ecosystem! Self-developed Cangjie programming language will make its debut Jun 21, 2024 pm 03:23 PM

According to news on June 21, this afternoon, Huawei Developer Conference 2024 will be officially opened. "Pure-blood Hongmeng" Harmony OS NEXT is naturally a top priority. According to the plan previously revealed by Yu Chengdong, the public beta may be officially announced this afternoon, and ordinary consumers can also try out "pure-blood Harmony". According to reports, the first batch of supported mobile phones are the Mate60 series and Pura70 series. It is worth noting that as a "pure-blooded Hongmeng", HarmonyOSNEXT has removed the traditional Linux kernel and AOSP Android open source code and developed the entire stack in-house. According to the latest report from Sina Technology, Huawei will also complete the last link of Hongmeng Ecosystem and expand its presence in the world.

Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Jun 12, 2024 pm 08:38 PM

Since the launch of ChatGLM-6B on March 14, 2023, the GLM series models have received widespread attention and recognition. Especially after ChatGLM3-6B was open sourced, developers are full of expectations for the fourth-generation model launched by Zhipu AI. This expectation has finally been fully satisfied with the release of GLM-4-9B. The birth of GLM-4-9B In order to give small models (10B and below) more powerful capabilities, the GLM technical team launched this new fourth-generation GLM series open source model: GLM-4-9B after nearly half a year of exploration. This model greatly compresses the model size while ensuring accuracy, and has faster inference speed and higher efficiency. The GLM technical team’s exploration has not

The Mistral open source code model takes the throne! Codestral is crazy about training in over 80 languages, and domestic Tongyi developers are asking to participate! The Mistral open source code model takes the throne! Codestral is crazy about training in over 80 languages, and domestic Tongyi developers are asking to participate! Jun 08, 2024 pm 09:55 PM

Produced by 51CTO technology stack (WeChat ID: blog51cto) Mistral released its first code model Codestral-22B! What’s crazy about this model is not only that it’s trained on over 80 programming languages, including Swift, etc. that many code models ignore. Their speeds are not exactly the same. It is required to write a "publish/subscribe" system using Go language. The GPT-4o here is being output, and Codestral is handing in the paper so fast that it’s hard to see! Since the model has just been launched, it has not yet been publicly tested. But according to the person in charge of Mistral, Codestral is currently the best-performing open source code model. Friends who are interested in the picture can move to: - Hug the face: https

See all articles