Home > Article > Backend Development > How to add characters to the beginning of a string in php
Two implementation methods: 1. Use the string connector "." to splice the specified character at the beginning of the string, and the syntax is "specified character. string"; 2. Use the substr_replace() function to add the specified character to the beginning of the string. To insert the specified character at the beginning of the string, you only need to set the second parameter of the function to the specified character, and set the third and fourth parameters to 0. The syntax is "substr_replace(string, specified character, 0, 0)" .
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
In PHP, you can use string concatenation or substr_replace() inserts to add characters to the beginning of the string.
Method 1: Use the string connector "." to splice
String connector .
can combine two or more strings are concatenated into a new string.
You only need to use the string connector "." to splice the specified characters at the beginning of the original string
<?php header("Content-type:text/html;charset=utf-8"); $str1="hello"; echo "原字符串:".$str1."<br>"; $ch="A"; echo "指定字符:".$ch."<br>"; $str=$ch.$str1; echo "在字符串首部增加指定字符后:".$str; ?>
Method 2: Use The substr_replace() function performs insertion
The substr_replace() function replaces part of a string with another 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.
#You only need to set the second parameter of the function to the specified character, the third parameter to 0, and the fourth parameter to 0.
<?php header("Content-type:text/html;charset=utf-8"); $str1="hello"; echo "原字符串:".$str1."<br>"; $ch="W"; echo "指定字符:".$ch."<br>"; $str=substr_replace($str1,$ch,0,0); echo "在字符串首部增加指定字符后:".$str; ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to add characters to the beginning of a string in php. For more information, please follow other related articles on the PHP Chinese website!