How to add string to variable in php

coldplay.xixi
Release: 2023-03-05 15:50:01
Original
3459 people have browsed it

php method to add a string to a variable: first specify the string before the insertion position; then specify the string after the insertion position; finally put the string before the insertion position, three characters after the insertion position, to be inserted Join the strings together.

How to add string to variable in php

[Related learning recommendations: php graphic tutorial]

php method to add a string to a variable:

First look at the simple replacement:

$str1 = "*3*";                //原字符串
$str2 = "abc";                //要添加的字符串
$str1 = str_replace("3",$str2."3",$str1);        //字符串替换
echo $str1;
Copy after login

is to replace 3 with abc3, But there is a premise for this: you must know that there is a "3" in the original string before you can replace it, otherwise it cannot be replaced.

So you need to use another method at this time: add a string at the specified position, for example:

<?php
/**
 * 指定位置插入字符串
 * @param $str  原字符串
 * @param $i    插入位置
 * @param $substr 插入字符串
 * @return string 处理后的字符串
 */
function insertToStr($str, $i, $substr){
    //指定插入位置前的字符串
    $startstr="";
    for($j=0; $j<$i; $j++){
        $startstr .= $str[$j];
    }
     
    //指定插入位置后的字符串
    $laststr="";
    for ($j=$i; $j<strlen($str); $j++){
        $laststr .= $str[$j];
    }
     
    //将插入位置前,要插入的,插入位置后三个字符串拼接起来
    $str = $startstr . $substr . $laststr;
     
    //返回结果
    return $str;
}
 
//测试
$str="hello zhidao!";
$newStr=insertToStr($str, 6, "baidu");
echo $newStr;
//hello baiduzhidao!
?>
Copy after login

Test instructions: insert a new string at the 6th string position, And output the final result

Related learning recommendations:php programming(video)

The above is the detailed content of How to add string to variable in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template