Home >Backend Development >PHP Problem >How to replace the first character in a string in php

How to replace the first character in a string in php

青灯夜游
青灯夜游Original
2021-05-11 17:42:023671browse

In PHP, you can use the substr_replace() function to replace the first character in a string, the syntax format is "substr_replace(original string, "replacement character",0,1)"; substr_replace() function You can replace part of a string with another string.

How to replace the first character in a string in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php replaces the first string in the string characters

<?php
$str1="abcdefg";
$str2=substr_replace($str1,"A",0,1);
echo $str2;
?>

Output:

Abcdefg

Related function description:

substr_replace() function replaces part of the string for another string.

Syntax:

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.

  • Positive numbers - Replace starting at the specified position in the string
  • Negative numbers - Replace starting at the specified position from the end of the string
  • 0 - Replace at the specified position in the string Start replacing the first character in
length

is optional. Specifies how many characters to replace. The default is the same as the string length.

  • Positive number - the length of the string being replaced
  • Negative number - indicates the number of characters from the end of the substring to be replaced string.
  • 0 - Insert instead of replace

Return value: Return the replaced string. If string is an array, the array is returned.

Recommended learning: "PHP Video Tutorial"

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

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