Home >Backend Development >PHP Problem >How to replace the first character with regular expression in php
In PHP, you can use the "preg_replace" function and the "/^./" regular expression to replace the first character. This function is used to perform a regular expression search and replacement. The syntax is " preg_replace('/^./', 'The first character after replacement', specified string)".
The operating environment of this tutorial: windows10 system, PHP7.1 version, DELL G3 computer
The preg_replace function performs a regular expression search and replace.
Syntax
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
Search for the part of subject that matches pattern and replace it with replacement.
Parameter description:
$pattern: The pattern to be searched, which can be a string or a string array.
$replacement: String or array of strings used for replacement.
$subject: The target string or string array to be searched and replaced.
$limit: Optional, the maximum number of substitutions for each subject string per pattern. The default is -1 (no limit).
$count: Optional, the number of times the replacement is performed.
Return value
If subject is an array, preg_replace() returns an array, otherwise it returns a string.
If a match is found, the replaced subject is returned, otherwise the unchanged subject is returned. If an error occurs, NULL is returned.
The example is as follows:
<?php $str = 'abcdefghi'; $str = preg_replace('/^./', 'A', $str); echo $str; ?>
Output result:
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to replace the first character with regular expression in php. For more information, please follow other related articles on the PHP Chinese website!