Page 1 of 1

String handling help

Posted: Tue Sep 07, 2004 4:02 am
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;

Posted: Tue Sep 07, 2004 5:15 am
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]));
?>

Posted: Tue Sep 07, 2004 5:33 am
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]

Posted: Tue Sep 07, 2004 5:35 am
by feyd
side note: quote those named array indices! :P