Log in

View Full Version : Replace text with variables in php



djnicemobile
02-12-2012, 12:32 AM
Hello, Im new to the forum.

I want to load text from a .txt file. Then replace the preset variables with the ones I put into a form.

I have a pre made template made already. EXAMPLE:

"Hi, my name is $name , I like to play $sport, and I live in $city"

I want to load that info from text, then change the variables to the actual words that was put in the form. (my text is way long that the text above, thats just a sample)

traq
02-12-2012, 04:20 AM
use sprintf():
text.txt:
Hi, my name is %s, I like to play %s, and I live in %s
<?php
$text = file_get_contents( 'text.txt' );
$name = 'Bob';
$sport = 'baseball';
$city = 'Baltimore';

print sprintf( $text,$name,$sport,$city );

djnicemobile
02-12-2012, 04:50 AM
thanks for replying

Im getting this

Warning: sprintf() [function.sprintf]: Too few arguments in ..... on line 50


This is my line 50

$sample is my .txt


print sprintf($sample, $linkz, $link2, $artist, $twitter, $song, $pic);




The text doc. is actually an HTML code. and the Form will replace when I have $linkz $artist etc.

traq
02-12-2012, 05:10 AM
what is the exact text you're using (i.e., the contents of $sample)?

the number of tokens ( %s ) in your text needs to match the number of additional arguments you pass to sprintf().
In your example (sprintf($sample, $linkz, $link2, $artist, $twitter, $song, $pic);), your text would need to contain six tokens.

djnicemobile
02-12-2012, 05:21 AM
It is quite long, its an email template. (long html code)...


or is there a way I can place the html code in the actual php file..

traq
02-12-2012, 07:06 AM
It is quite long, its an email template. (long html code)...


or is there a way I can place the html code in the actual php file..

no, it's better to keep it separate.

are you trying to use those same variables in several places in the template? In that case, you can number them... here's an example:

<?php
$text = 'My name is %1$s, and I like %2$s. Remember my name - %1$s.';
$name = 'Joe Cool';
$favorite = 'PHP';

printf( $text,$name,$favorite );
// prints "My name is Joe Cool, and I like PHP. Remember my name - Joe Cool."

you'll still need to pass as many extra arguments as there are unique tokens in the template.