lleoun
lleoun

Reputation: 477

Getting text from a file and giving value to it

Been looking for the answer to my question in the posts but I cannot find something to guide me. Sorry if this has been asked before.

I have a html file called email.html. In the contents I have #user# #pass# and #text#

What I need to do is get #user# #pass# and #text# and change them for the real thing. The real things is data coming from database.

I've been thinking in a php file with

$email = file_get_contents('email.html'); 

But then I get lost, anyone can please tell me how to get the ## tags and give them value?

Please guide this sad student ;)

Thansk lot !

Upvotes: 1

Views: 94

Answers (3)

Dereleased
Dereleased

Reputation: 10087

As long as those strings are guaranteed unique, you could simply have something like this:

Assuming your array of data for replacement looks like:

Array(
    'user' => '[email protected]',
    'pass' => 'foo',
    'text' => 'Welcome Mr. Example!',
);

then

foreach ($data as $tag => $datum) {
    $email = str_replace('#' . $tag . '#', $datum, $email);
}

EDIT: xil brings up a good point: arrays.

function addHashMarks($v) { return "#{$v}#"; }
$email = str_replace(
    array_map('addHashMarks', array_keys($data)),
    array_values($data),
    $email
);

IMO, there's no reason to fire up the REGEX parser if what you're doing doesn't actually use regular expressions; str_replace is MUCH faster.

EDIT: I had actually intended to do the addHashMarks part with an anonymous function, but (a) those are 5.3+ only and (b) I didn't want to introduce too many concepts at once -- but seriously, go check out anonymous functions.

Upvotes: 2

xil3
xil3

Reputation: 16439

Could do this:

$email = file_get_contents('email.html');

$patterns = array();
$patterns[0] = '#user#';
$patterns[1] = '#pass#';
$patterns[2] = '#text#';

$replacements = array();
$replacements[2] = 'user';
$replacements[1] = 'password';
$replacements[0] = 'your text';

$newEmail = preg_replace($patterns, $replacements, $email);

More info here:

http://php.net/manual/en/function.preg-replace.php

Upvotes: 1

checkandy
checkandy

Reputation: 27

If the format of this text file was a little clearer, it would be easier to help.

Look into the php function strtr()

Upvotes: 0

Related Questions