I cannot find my error here.
I have a simple text file containing a few dates (one per line) and I’m looking to replace a PHP variable in a markdown file with a list of the dates.
// get all meeting dates
$file = 'pcdates.txt';
if (file_exists($file)) {
$dates = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$dates = array_map('trim', $dates);
$pcdates = implode(', ', $dates);
// $pcdates is as expected
}
// get the markdown and replace dates
require_once 'Parsedown.php';
$file = 'md/parish-council.md';
include 'inc/getmdown.inc.php';
if (file_exists($file)) {
$text = file_get_contents($file);
$Parsedown = new Parsedown();
$output = $Parsedown->text($text);
$output = str_replace('{pcdates}', $pcdates, $output);
echo $output, "\n";
}
The markdown file include the following line:
Forthcoming meetings will be {pcdates}.
And what is displayed is in the HTML:
<p>Forthcoming meetings will be {pcdates}.</p>
I cannot for the life of me see what is wrong. I have echoed $pcdates and it contains the expected list of dates. It looks as though the string replace is not happening.
I cannot see what’s wrong. I have another very similar page where I have used this technique and it works there.
What’s the value of $output just before the str_replace? is Parsedown doing something to obscure the braces? (Like… HTML entity replacing them?)
1 Like
$output seems to be the same both before and after the str_replace. I don’t think Parsedown is doing anything with the braces; as I say the same technique worked on another page. I’ve changed the variable name without any effect. The only difference that I can see, apart from the variable names, is that the MD file that it works on is only 405 bytes, and the one that doesn’t is 3392.
Things i would test at that point:
var_dump(array_map('ord',str_split($output)));
(and for sanity, do the same with the needle string from your str_replace)
Just make sure those curly braces are the right ASCII values and that your markdown file isn’t trying to use some odd not-quite-a-brace brace…(Macs and their fancy quote marks always make me leery of stuff like this)
Also, try adding a $count parameter to the str_replace. If its a 0 after the replace, str_replace found nothing to replace. If it’s a 1, it tried to replace something and screwed up.
2 Likes
Okay, problem solved. I omitted to remove the line
include 'inc/getmdown.inc.php';
which echoes $output without a replace. What I failed to notice was it was outputting the page twice, once without the replace, once with.

Thanks, Marc
3 Likes