String handling help

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
harsha
Forum Contributor
Posts: 103
Joined: Thu Jul 11, 2002 1:35 am
Location: Bengaluru (Bangalore) > Karnataka > India

String handling help

Post by harsha »

$row[TemplateBody] = " Welcome to the Digital libraryYour login information is as follows: User Name: $Username Password: $Password ";

$Passwd = "hello";
$Usr = "Harsha";

str_replace(); how to replace the $Username and $Password with the values of $Passwd and $Usr;
AimsB
Forum Newbie
Posts: 12
Joined: Thu Jul 08, 2004 9:39 am
Location: UK

Post by AimsB »

You could use the eval() statement. Save the variable like this:

Code: Select all

<?
$row[TemplateBody] = 'Welcome to the Digital libraryYour login information is as follows: User Name: $Usr Password: $Passwd ';
?>
The single quotes will mean that the variables $Usr and $Passwd aren't replaced at that time, so they will be saved literally as "$Usr" and "$Passwd". Then later on you assign your $Passwd and $Usr variables, and then after that run the following bit of code:

Code: Select all

<?
eval ("\$row[TemplateBody]= "$row[TemplateBody]";");
?>
Which will make it then evaluate the original string, but this time with the correct values.

Alternatively, you may want the simpler solution! In your original string just remove the dollar signs and make the words more unique, for example you could say "User Name: MyUserName Password: MyPassWord"; and then do:

Code: Select all

<?
$row[TemplateBody] = ereg_replace("MyUserName", $Usr, ereg_replace("MyPassWord", $Passwd, $row[TemplateBody]));
?>
User avatar
m3mn0n
PHP Evangelist
Posts: 3548
Joined: Tue Aug 13, 2002 3:35 pm
Location: Calgary, Canada

Post by m3mn0n »

It's as simple as:

Code: Select all

<?php
$defined_username = "php_n00b";
$row['TemplateBody'] = str_replace ("{{username}}", $defined_username, $row['TemplateBody'] );
?>
If you read up at [php_man]str_replace[/php_man](), you would've found out about that. ;)

[big_search]string manipulation tutorial php[/big_search]
Last edited by m3mn0n on Tue Sep 07, 2004 5:35 am, edited 1 time in total.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

side note: quote those named array indices! :P
Post Reply