Replace characters in a PHP string

One of the questions you have asked us is how you can replace characters in a string PHP. So let’s get to work.

The idea is that we start with a string in which there are numbers and characters in ‘x’. The idea is to be able to replace the ‘x’ characters of the string with a number and thus be able to have a complete number. That is, we would start from something like ‘1245xxxx’ and we would get something like ‘12458937’.

The first thing will be to define the base chain:

$list = '12345xxxxx';
echo 'Initial String: '.$list."n";

Once we have the string, what we are going to do is validate if there are ‘x’ characters within it. For this we rely on the function strpos() which receives as parameters the string and the character to search for.

strpos($list, 'x');

If it has an ‘x’, what we will do is replace the ‘x’ with a random number. To generate a random number in PHP what we do is based on the function rand

rand(0,9);

The function that will help us to replace the character ‘x’ with the random number will be preg_replace. This function receives a regular expression with the element to search for, the value with which we are going to replace it (in our case the random number), the string on which we want to perform the substitution and how many times we want to perform the substitution.

$list = preg_replace('/x/', rand(0,9), $list, 1);

If we do not indicate that it only substitutes once, what it will do is replace all the ‘x’ with the same random number. But since we want to enter several random numbers, we will indicate that it only substitutes the first ‘x’ it finds.

This is why we will have to create a loop that repeats the same operation as long as no ‘x’ characters appear within the string.

while (strpos($list, 'x')) {
  $list = preg_replace('/x/', rand(0,9), $list, 1);
}

In this way we will have already managed to replace characters in a string PHP.