PHP字符串中插入子字符串方法总结 原创,fontcolor
本文实例讲述了PHP字符串中插入子字符串方法。分享给大家供大家参考,具体如下:
首先来看看一个网上常见的方法:
方法一:字符串遍历
function str_insert($str, $i, $substr) { for($j=0; $j<$i; $j++){ $startstr .= $str[$j]; } for ($j=$i; $j<strlen($str); $j++){ $laststr .= $str[$j]; } $str = ($startstr . $substr . $laststr); return $str; } $str="1234567890"; $sstr="new_word"; echo str_insert($str,5,$sstr);//输出:12345new_word67890
上述方法采用了字符串遍历重组来实现子字符串的插入功能。
再来看看帮客之家给出的一个改进方法:
方法二:采用substr函数进行截取与组合
function str_insert2($str,$i,$substr){//方法二:substr函数进行截取 $start=substr($str,0,$i); $end=substr($str,$i); $str = ($start . $substr . $end); return $str; //return substr($str,0,$i).$substr.substr($str,$i);//上述代码可综合成这一句 } $str="1234567890"; $sstr="new_word"; echo str_insert2($str,5,$sstr);//输出:12345new_word67890
该方法直接使用substr函数进行字符串的截取,再进行字符串的拼装,从而实现子字符串的插入效果。
最后帮客之家给大家提供一个最直接的方法:
方法三:直接使用substr_replace函数进行子字符串的插入
echo substr_replace($str,$sstr,5,0); //此处直接输出:12345new_word67890
更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP数组(Array)操作技巧大全》、《PHP数据结构与算法教程》、《PHP数学运算技巧总结》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools