php can add characters to strings. Two implementation methods: 1. Use the string connector "." to splice the specified character to the beginning or end of the string. The syntax is "specified character. string" or "string. specified character"; 2. use substr_replace The () function inserts the specified character at the specified position of the string. The syntax is "substr_replace(string, specified character, specified position, 0)". The value at the specified position can be 0, negative or positive.
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
In PHP, you can add characters to a string ;This can be achieved through string splicing or substr_replace() insertion.
Method 1: Use the string connector "." to splice
The string connector ".
" can combine two or more More than three strings are concatenated into a new string.
The string concatenator ".
" can splice the specified characters to the beginning or end of the string.
<?php header("Content-type:text/html;charset=utf-8"); $str1="1234"; echo "原字符串:".$str1."<br>"; $ch="A"; echo "指定字符:".$ch."<br><br>"; $str=$ch.$str1; echo "在字符串开头添加指定字符:".$str."<br>"; $str=$str1.$ch; echo "在字符串末尾添加指定字符:".$str; ?>
Method 2: Use the substr_replace() function to insert
The substr_replace() function replaces part of the string with another a string.
substr_replace(string,replacement,start,length)
Parameters | Description |
---|---|
string | Required . Specifies the string to check. |
replacement | Required. Specifies the string to be inserted. |
start | Required. Specifies where in the string to begin replacement.
|
length | Optional. Specifies how many characters to replace. The default is the same as the string length.
|
Return value: Returns the replaced string.
Use the substr_replace() function to insert the specified character at any specified position; you only need to set the second parameter of the function to the specified character, and the third parameter to Specify the position and set the fourth parameter to 0.
<?php header("Content-type:text/html;charset=utf-8"); $str1="1234"; echo "原字符串:".$str1."<br>"; $ch="@"; echo "指定字符:".$ch."<br><br>"; $str=substr_replace($str1,$ch,0,0); echo "在字符串开头添加指定字符:".$str."<br>"; $str=substr_replace($str1,$ch,strlen($str1),0); echo "在字符串末尾添加指定字符:".$str."<br>"; $str=substr_replace($str1,$ch,1,0); echo "在第一个字符后添加指定字符:".$str."<br>"; $str=substr_replace($str1,$ch,-1,0); echo "在倒数第一个字符前添加指定字符:".$str."<br>"; ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of Is it possible to add characters to a string in php?. For more information, please follow other related articles on the PHP Chinese website!