search
HomeBackend DevelopmentPHP TutorialPHP中str_replace函数用法细节

​PHP中str_replace函数使用小结

在实际的程序开发中,执行字符串替换操作是一件非常经常的事,对str_replace函数的实用也会非常频繁。

这段时间在看《PHP和MySQL Web开发》一书看到str_replace讲解,一段小提示写到:可以为str_replace的三个都使用数组传入,但讲解比较简单,于是决定自己的试验一下该函数在各个参数传入数组时的执行结果。

函数原型:

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


needle:要被替换的字符串, new_needle:替换用的字符串, haystack:操作字符串,count:替换次数【可选参数】

我们重点试验前三个在使用数组是的执行方式:

在都不使用数组时,该函数直接使用new_needle替换所有的needle并返回替换后的字符串。如:str_replace("m","n","my name is jim!")返回ny nane is jin!

1、只对needle使用数组。

示例:

str_replace(array('m','i'),'n',"my name is jim!");

返回:ny nane ns jnn!
可以看出,函数顺序性的对数组中每个字符串进行替换,并返回替换后的字符串。

2、只对new_needle使用数组。

示例:str_replace('m',array('n','z'),"my name is jim!\n");返回:Arrayy naArraye is jiArray!
该替换比较有意思,如果只对第二个参数使用数组则函数将其作为字符串Array进行使用,将所有的needle替换为了数组。

3、只对haystack使用数组。

示例:

str_replace("m","n",array("my name is jim!","the game is over!"));

该语句执行结果返回一个数组,即分别为传入的两个字符串替换后的结果。
如果输出数组内容会看到:ny nane is jin! the gane is over!

4、对needle和new_needle都使用数组。

示例:

str_replace(array("m","i"),array("n","z"),"my name is jim!");

返回:ny nane zs jzn!
查看执行结果可以发现,如果前两个参数都使用数组则函数把数组各个对象项字符 串进行了替换,及needle的第一项替换为new_needle的第一项。以此类推。

如果needle数组比new_deedle长,例如:str_replace(array("m","i","s"),array("n","z"),"my name is jim!");返回:ny nane z jzn!可见,对于needle数组多出来的字符串被替换为了空串。
如果new_needle数组比needle长,例如:str_replace(array("m","i"),array("n","z","x"),"my name is jim!")返回ny nane zs jzn!可见new_needle多余的项被忽略。

5、三个参数都使用数组。

例如:

str_replace(array("m","i"),array("n","z"),array("my name is jim!","the game is over"));

返回的数组内容:ny nane zs jzn!the gane zs over
这个比较好理解,对两个字符串分别执行替换


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
What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

What is the importance of setting the httponly flag for session cookies?What is the importance of setting the httponly flag for session cookies?May 03, 2025 am 12:10 AM

Setting the httponly flag is crucial for session cookies because it can effectively prevent XSS attacks and protect user session information. Specifically, 1) the httponly flag prevents JavaScript from accessing cookies, 2) the flag can be set through setcookies and make_response in PHP and Flask, 3) Although it cannot be prevented from all attacks, it should be part of the overall security policy.

What problem do PHP sessions solve in web development?What problem do PHP sessions solve in web development?May 03, 2025 am 12:02 AM

PHPsessionssolvetheproblemofmaintainingstateacrossmultipleHTTPrequestsbystoringdataontheserverandassociatingitwithauniquesessionID.1)Theystoredataserver-side,typicallyinfilesordatabases,anduseasessionIDstoredinacookietoretrievedata.2)Sessionsenhances

What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

See all articles

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools