Replacing Substrings

You want to replace a substring with a different string.

Use substr_replace($old_string, $new_string, $star, $length). Without the $length argument, substr_replace() replaces everything from $start to the end of the string. If $length is specified, only that many characters are replaced.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
$hello = 'Hello World';
echo $hello, "<br />";
echo substr_replace($hello, 'John', 6), "<br />";
echo substr_replace($hello, 'John', 6, 5), "<br />";

// start counting from the end
echo substr_replace($hello, 'John', -6), "<br />";
echo substr_replace($hello, 'John', -6, 5), "<br />";

// the new substring is inserted at the start
echo substr_replace($hello, 'John: ', 0, 0), "<br />";

$credit_card = '4111 1111 1111 1111';
echo $credit_card, "<br />";
echo substr_replace($credit_card, 'xxxx', 0, strlen($credit_card)-4), "<br />";
?>
</p>
</body>
</html>

View the effect


Strings | Introduction | Formatting Strings | Converting to and from Strings | Finding the Length of a String | Accessing Substrings | Extracting Substrings | Replacing Substrings | Taking Strings Apart | Processing a String One Byte at a Time | Reversing a String by Word or Byte | Controlling Case | Trimming Blanks from a String | Wrapping Text at A Certain Line Length
© 2008: Hann So
email: hso@voyager.deanza.edu