Reputation: 2737
Is it possible to replace parts of a string with the content of an include file?
For example, this is my string
$string = '<p>The article title goes here bla bla bla...</p>{{ADD_AUTHOR_DETAILS_}}<p>The article body goes here...</p>';
Basically, I want to replace {{ADD_AUTHOR_DETAILS_}}
with the content of an include
file. The include file contains html tags, text, etc...
Is this possible in php and if yes, how?
EDIT
Some are asking what's inside the include file (php file). This is a sample
<div class="article-author"><?php
if ( !empty($artistphoto) ) { ?>
<img class="round" src="<?php echo $config['path']['artist_image'] . $artistphoto; ?>" width="" height="" alt="<?php echo $artistname; ?>"><?php
} else { ?>
<div class="placeholder round"><span></span></div><?php
} ?><span><a href="<?php echo $config['reference']['library_author'] . $artisthref; ?>"><?php echo $artistname; ?></a></span>
</div>
Upvotes: 1
Views: 138
Reputation: 115
You can use output buffering functions. See ob_start() and ob_get_clean()
<?php
ob_start();
include('path/to/your/file.php');
$content = ob_get_clean();
$string = '<p>The article title goes here bla bla bla...</p>{{ADD_AUTHOR_DETAILS_}}<p>The article body goes here...</p>';
echo str_replace('{{ADD_AUTHOR_DETAILS_}}', $content, $string);
OP said "include" not file_get_contents, though perhaps the other answer maybe what you're looking for.
Upvotes: 2
Reputation: 7485
You can replace multiple substrings with strtr.
<?php
$string = '@@HEADING@@, welcome, @@BODY@@, thankyou.';
$output = strtr($string, array(
'@@HEADING@@' => file_get_contents('/tmp/heading.txt'),
'@@BODY@@' => file_get_contents('/tmp/body.txt')
));
print $output;
Upvotes: 1
Reputation: 6058
You can use file_get_contents to load the contents of a file, then use str_replace to replace the part of your string.
$myString = 'This is a lovely string... But [REPLACE_THIS]';
$fileContents = file_get_contents('my_replacement.txt');
$myString = str_replace('[REPLACE_THIS]', $fileContents, $myString);
Upvotes: 2