user198729
user198729

Reputation: 63686

How to replace the characters in fixed positions in PHP?

I want to replace with the 4~8 characters of a string with *,how to do it?

HelloWorld

=>

Hell****ld

Upvotes: 4

Views: 11534

Answers (7)

Vitalicus
Vitalicus

Reputation: 1389

<?php
$e=str_split("HelloWorld");
$e[3]="*";
$e[4]="*";
$e[5]="*";
echo implode($e);
?>

User can change only the characters that he need.

Upvotes: -1

muruga
muruga

Reputation: 2122

<?php
$var="HelloWorld";
$pattern="/oWor/";
$replace="****";
echo preg_replace($pattern,$replace,$var);
?>

Upvotes: 0

Pavunkumar
Pavunkumar

Reputation: 5345

$var="HelloWorld";
$result=substr_replace($var, '****', 4,4 ) . "<br />\n";

Upvotes: -1

ghostdog74
ghostdog74

Reputation: 343141

$str="HelloWorld";
print preg_replace("/^(....)....(.*)/","\\1****\\2",$str);

Upvotes: -1

Kyle Decot
Kyle Decot

Reputation: 20835

You'll need to use substr_replace().

$str = substr_replace("HelloWorld","****",3,-2);

Upvotes: -1

Haim Evgi
Haim Evgi

Reputation: 125644

use

substr_replace()

like

substr_replace($string, '****', 4 , 4);

read more :

http://php.net/manual/en/function.substr-replace.php

Upvotes: 10

Crozin
Crozin

Reputation: 44406

$string = 'HelloWorld';

for ($i = 4; $i <= 8; ++$i) {
    $string[$i] = '*';
}

But there is many, many more ways to do that.

Upvotes: -1

Related Questions