Home php教程 php手册 PHP字符串操作入门教程

PHP字符串操作入门教程

Jun 21, 2016 am 09:07 AM
echo nbsp

教程|入门教程|字符串

无论哪种语言,字符串操作都是一个重要的基础,往往是简单而重要。正像人说话一样,一般有形体(图形界面),有语言(print 字符串?),显然字符串能解释更多的东西。PHP提供了大量的字符串操作函数,功能强大,使用也比较简单,详细请参看 http://cn2.php.net/manual/zh/ref.strings.php . 以下将简单的讲述它的功能和特性。
弱类型
PHP是弱类型语言,所以其它类型的数据一般可以直接应用于字符串操作函数里,而自动转换成字符串类型,进行处理,如:


PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

echo substr("1234567", 1, 3); 

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

echo substr(123456,1, 3); 

是一样的

定义
一般用双引号或单引号标识一个字符串。比如

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

$str = "i love u";
$str = 'i love u'; 


它者两者是有一些区别的。后者将一切单引号的内容都会当作字符处理;前者则不然。比如

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

$test = "iwind";
$str = "i love $test";
$str1 = 'i love $test';
echo $str; //将得到 i love iwind
echo $str1; //将得到 i love $test 


同样的以下两个例子的行为也不一样的:

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

echo "i love \test"; // 将得到 i love est,已经将\t视为转义
echo 'i love \test'; // 将得到 i love \test 


从而可以简单认为双引号里的内容是经过“解释”过的,单引号的是“所见即所得”的。显而易见,双引号形式的更为灵活一些,当然单引号会适用于一些特殊的场合,这里就不作阐述了。

输出
PHP里的输出最常用的是echo,print.两者都不是真正的函数,而是语言构造,所以调用时不必用双括号(比如echo("test");print("test")).在输出的时候两者都可以实现赋值:

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

echo $str="test"; //一方面输出test,一方面把"test"赋给字符串变量 $str
print $str="test"; 


两者除了名字不一样外,还是有其它区别的。print具有返回值,一直返回1,而echo没有,所以echo比print要快一些:

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

$return = print "test";
echo $return; // 输出1 


也正因为这个原因,print能应用于复合语句中,而echo不能:

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

isset($str) or print "str 变量未定义"; // 将输出"str 变量未定义"
isset($str) or echo "str 变量未定义";// 将提示分析错误 


echo一次可输出多个字符串,而print则不可以:

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

echo "i ","love ","iwind"; // 将输出 "i love iwind"
print "i ","love ","iwind"; // 将提示错误 


echo,print还可以输出被称作“文档句法”的字符串,句法如:

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

echo ...
字符串内容
...
标签名称; 


比如

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

echo i love iwind
test; 


要注意的是语句开始和结束的两个标签名称是一样的,且后一个标签名称前不能有空白,即要顶格写。文档句法输出的内容识别变量名称和常用符号,大致形同双引号的作用。

输出echo,print外,PHP还提供了一些格式化字符串的函数,比如printf,sprintf,vprintf,vsprintf,在这里不作详解。

连接
两个以上的字符串连接用"."操作符,依字符串的顺序形成新的字符串。

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

$str = "i " . "love " . "iwind";
这里的$str 就是 "i love iwind";字符串。当然,还可以使用 .= 操作符:
$str = ""; // 初始化
$str .= "i love iwind"; 


这里用到了初始化,是因为未定义变量在使用时会产生一个notice错误,""或者null可以简单地代表空字符串。

长度
PHP提供strlen函数来计算字符串的长度:

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

$str = "test";
echo strlen($str); // 将输出 4 

有点奇怪的是strlen将中日等汉字以及全角字符都当作两个或四个长度计算。好在mbstring或icon两个函数可以帮助解决这个问题,比如:

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

$len = iconv_strlen($str, "GBK");
$len = mb_strlen($str, "GBK"); 

注:mbstring模块提供了大量的对含有多字节字符的字符串的处理函数,推荐多加应用,由于这篇文章讲的是字符串入门,所以不打算详细解说。

分隔与连接
PHP允许你把一个字符串按照一个分隔符进行分隔成一个数组,或者将一个数组组合成一个字符串。看下面的例子:

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

$str = "i love iwind";
$array = explode(" ", $str); 

上面的explode函数,就把$str字符串按空格字符进行分隔,结果返回一个数组 $array:array("i", "love", "iwind").与explode函数有类似功能的有:preg_split(), spliti(), split()等函数。

与此相反的,implode和join则能把一个数组结合成一个字符串,他们是具有完全相同功能的函数。

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

$array = array("i", "love", "iwind");
$str = implode(" ", $array);
例中的implode函数将数组$array的每个元素用空格字符进行连接,返回一个字符串 $str: "i love iwind". 


裁剪
一个字符串首和尾,可能不是你想要的部分,就可以用trim,rtrim,ltrim等函数,分别去除一个字符串两端空格,一个字符串尾部空格,一个字符串首部空格。

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

echo trim(" i love iwind "); // 将得到 "i love iwind"
echo rtrim(" i love iwind "); // 将得到 " i love iwind"
echo ltrim(" i love iwind "); // 将得到 "i love iwind " 

其实这三个参数不仅可以去除字符串首尾的空格,还可以去除它们的第二个参数指定的字符,如:

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

echo trim(",1,2,3,4,", ","); // 将得到 1,2,3,4 两端的","号被裁掉了。 


有时还会看到有人使用chop这个函数,其实它是rtrim的同义函数。

大小写
对于英文字母来说,可以用strtoupper,strtolower将其转变成大写或小写。

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

echo strtoupper("i love iwind"); // 将得到 I LOVE IWIND
echo strtolower("I LOVE IWIND"); // 将得到 i love iwind 


比较
一般可以用 !=, == 比较两个对象是否相等,只所以说是两个对象,是因为它们不一定全部为字符串,也可以为整型等等。比如

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

$a = "joe";
$b = "jerry";
if ($a != $b)
{
echo "不相等";
}
else
{
echo "相等";

如果用 !==,===(可以看到多了一个等号)比较的话,两个对象的类型要严格相等才能返回true;否则用==,!=则会将字符串自动转换成相应的类型,以便进行比较.

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

22 == "22"; // 返回 true
22 === "22"; // 返回false
//正因为这样,所以我们的程序时常会发生一些想不到的"意外":
0 == "我爱你"; // 返回true
1 == "1 我爱你";// 返回true 


PHP里还有这样一组用于字符串比较的函数:strcmp,strcasecmp,strncasecmp(), strncmp(),它们都是如果前者比后者大,则返回大于0的整数;如果前者比后者小,则返回小于0的整数;如果两者相等,则返回0.它们比较的原理与其它语言的规则都是一样的。
strcmp是用于区分大小写(即大小写敏感)的字符串比较:

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

echo strcmp("abcdd", "aBcde"); // 返回 1 (>0), 比较的是 "b"和"B" 


strcasecmp用于不区分大小写的字符串比较:

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

echo strcasecmp("abcdd", "aBcde"); // 返回 -1 (


strncmp用于比较字符串的一部分,从字符串的开头开始比较,第三个参数,为要比较的长度:

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

echo strncmp("abcdd", "aBcde", 3); // 返回 1 (>0), 比较了 abc 和 aBc 


strncasecmp用于不区分大小写的比较字符串的一部分,从字符串的开头开始比较,第三个参数,为要比较的长度:

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

echo strncasecmp("abcdd", "aBcde", 3); // 返回 0, 比较了 abc 和 aBc, 
由于不区分大小写,所以两者是相同的。

还有一种情况是单单比较字符串大小,达不到我们预定的要求,比如照常理 10.gif 会比 5.gif 大,但如果应用上面几个函数,就会返回 -1,即表示 10.gif比5.gif,针对这种情况,PHP提供了两个自然对比的函数strnatcmp,strnatcasecmp:

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

echo strnatcmp("10.gif", "5.gif"); // 返回 1 (>0)
echo strnatcasecmp("10.GIF", "5.gif"); // 返回 1 (>0) 


替换
替换的意义在于将一个字符串的一部分进行改变,使之成为别外一个新的字符串,以满足新的要求。PHP里通常用str_replace("要替换的内容", "要取代原内容的字符串", "原字符串")进行替换。

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

echo str_replace("iwind", "kiki", "i love iwind, iwind said"); // 将输出 "i love kiki, kiki said" 

即将 原字符串中的所有"iwind"都替换成了"kiki".

str_replace是大小写敏感的,所以对你不能设想用 str_replace("IWIND", "kiki",...)替换原字符串中的"iwind".

str_replace还可以实现多对一,多对多的替换,但无法实现一对多的替换:

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

echo str_replace(array("iwind", "kiki"), "people", "i love kiki, iwind said"); 

将会输出
i love people, people said
第一个参数中的array("iwind", "kiki")都被替换成了"people"


PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

echo str_replace(array("iwind", "kiki"), array("gentle man", "ladies"), "i love kiki, iwind said"); 

输出 i love ladies, gentle man said 。也就是说第一个数组中的元素被第二个数组中的相对应的元素替换掉了,如果有一个数组比另一个数组元素数要少,那么不足的都会当作空来处理。

与此有些类似的是strtr,用法请参阅手册,它们的比较请参阅 http://diary.4kiki.net/index.php?action=info&id=372 .

此外,PHP还提供了substr_replace,实现替换一部分的字符串。语法如下:
substr_replace (原字符串, 要替代的字符串, 开始替换的位置 [, 替换的长度])
其中,开始替换的位置从0开始计算,应该小于原字符串的长度。要替换的长度是可选的。

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

echo substr_replace("abcdefgh", "DEF", 3); // 将输出 "abcDEF"
echo substr_replace("abcdefgh", "DEF", 3, 2); // 将输出 "abcDEFfgh" 

第一个例子中,从第三个位置(即"d")开始替换,从而把 "defgh"都替换成了“DEF”
第二个例子中,也是从第三个位置(即"d")开始替换,但只能替换2个长度,即到e,所以就把"de"替换成了"DEF".

PHP还提供了preg_replace,preg_replace_callback,ereg_replace,eregi_replace等函数应用正则表达式来完成字符串替换,用法请参考手册。

查找与匹配
PHP里用于查找或者匹配或者定位的函数非常多,它们都有不同的意义。这里只讲述用得比较多的strstr,stristr.后者与前者的功能,返回值都一样,只是不区分大小写。
strstr("母字符串", "子字符串")用来查找子字符串在母字符串中第一次出现的位置,并返回母字符串中从子字符串开始到母字符串结束的部分。比如
echo strstr("abcdefg", "e"); //将输出 "efg"
如果找不到子字符串,则返回空。因为可以用来判断一个字符串中是否含有另外一个字符串:

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

$needle = "iwind";
$str = "i love iwind";
if (strstr($str, $needle))
{
echo "里面有 iwind";
}
else
{
echo "里面没有 iwind";
}
将会输出"里面有 iwind" 


HTML相关
1,htmlspecialchars($string)
这是它的最简单用法,将字符串中的一些特殊字符(顾名思义)&,',"转换成它们对应的HTML实体形式:

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

$str = "i love kiki, iwind said.";
echo htmlspecialchars($str); 

将会输出
i love kiki, iwind said.

2,htmlentities($string)
将所有能转换成实体形式的字符都转换成实体形式。

3,html_entity_decode($string);
PHP4.3.0以后加入的具有与htmlentities($string)相反的功能。

4,nl2br($string)
将字符串中所有换行符转变成
+ 换行符。如:

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

$str = "i love kiki,\n iwind said.";
echo nl2br($str); 

将会输出
i love kiki,

iwind said.


加密
加密字符串最常用的就是md5了,它将一个字符串转换成一个长32位的唯一的字符串。

PHP:  [Copy to clipboard]
--------------------------------------------------------------------------------

echo md5("i love iwind"); // 将输出 "2df89f86e194e66dc54b30c7c464c21c" 


PHP5给md5加了第二个参数,从而使它可以输出16位的加密后的字符串。


到这里,这篇字符串操作入门教程就算结束了,但上面讲的这些还只是它的冰山一角,特别是PHP5之后增加了大量的新功能,所以需要我们不断的去学习它才有可能很好的应用。



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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Solution: Your organization requires you to change your PIN Solution: Your organization requires you to change your PIN Oct 04, 2023 pm 05:45 PM

The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

How to adjust window border settings on Windows 11: Change color and size How to adjust window border settings on Windows 11: Change color and size Sep 22, 2023 am 11:37 AM

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

How to change title bar color on Windows 11? How to change title bar color on Windows 11? Sep 14, 2023 pm 03:33 PM

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

OOBELANGUAGE Error Problems in Windows 11/10 Repair OOBELANGUAGE Error Problems in Windows 11/10 Repair Jul 16, 2023 pm 03:29 PM

Do you see "A problem occurred" along with the "OOBELANGUAGE" statement on the Windows Installer page? The installation of Windows sometimes stops due to such errors. OOBE means out-of-the-box experience. As the error message indicates, this is an issue related to OOBE language selection. There is nothing to worry about, you can solve this problem with nifty registry editing from the OOBE screen itself. Quick Fix – 1. Click the “Retry” button at the bottom of the OOBE app. This will continue the process without further hiccups. 2. Use the power button to force shut down the system. After the system restarts, OOBE should continue. 3. Disconnect the system from the Internet. Complete all aspects of OOBE in offline mode

How to enable or disable taskbar thumbnail previews on Windows 11 How to enable or disable taskbar thumbnail previews on Windows 11 Sep 15, 2023 pm 03:57 PM

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

Display scaling guide on Windows 11 Display scaling guide on Windows 11 Sep 19, 2023 pm 06:45 PM

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

10 Ways to Adjust Brightness on Windows 11 10 Ways to Adjust Brightness on Windows 11 Dec 18, 2023 pm 02:21 PM

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

How to Fix Activation Error Code 0xc004f069 in Windows Server How to Fix Activation Error Code 0xc004f069 in Windows Server Jul 22, 2023 am 09:49 AM

The activation process on Windows sometimes takes a sudden turn to display an error message containing this error code 0xc004f069. Although the activation process is online, some older systems running Windows Server may experience this issue. Go through these initial checks, and if they don't help you activate your system, jump to the main solution to resolve the issue. Workaround – close the error message and activation window. Then restart the computer. Retry the Windows activation process from scratch again. Fix 1 – Activate from Terminal Activate Windows Server Edition system from cmd terminal. Stage – 1 Check Windows Server Version You have to check which type of W you are using

See all articles