How To Replace a Group of Characters by Another Group?

deepak singh
Posts: 686
Joined: Fri Sep 30, 2016 4:19 pm

How To Replace a Group of Characters by Another Group?

Postby deepak singh » Sat Oct 01, 2016 5:12 pm

How To Replace a Group of Characters by Another Group?

rameshkhd
Posts: 1279
Joined: Sun Aug 28, 2016 10:45 am

Re: How To Replace a Group of Characters by Another Group?

Postby rameshkhd » Sat Oct 01, 2016 5:14 pm

While processing a string, you may want to replace a group of special characters with some other characters. For example, if you don't want to show user's email addresses in the original format to stop email spammer collecting real email addresses, you can replace the "@" and "." with something else. PHP offers the strtr() function with two format to help you:
• strtr(string, from, to) - Replacing each character in "from" with the corresponding character in "to".
• strtr(string, map) - Replacing each substring in "map" with the corresponding substring in "map".
Here is a PHP script on how to use strtr():
<?php
$email = "joe@dev.pickzycenter.moc";
$map = array("@" => " at ", "." => " dot ");
print("Original: $email\n");
print("Character replacement: ".strtr($email, "@.", "#_")."\n");
print("Substring replacement: ".strtr($email, $map)."\n");
?>
This script will print:
Original: joe@dev.pickzycenter.moc
Character replacement: joe#dev_pickzycenter_moc
Substring replacement: joe at dev dot pickzycenter dot moc
To help you to remember the function name, strtr(), "tr" stands for "translation".


Return to “PHP”

Who is online

Users browsing this forum: No registered users and 3 guests