I have a template file that uses the structure [FIRSTNAME] [LASTNAME]
开发者_Python百科etc etc.... and I will be doing a search and replace on it. One thing that I would like to do is that when the template get's sent back, IF I haven't stipulated, [FIRSTNAME].... it still shows in the template... I would like to make it NULL IF I haven't stipulated any data to that variable.
in my code i'm using the FILE_GET_CONTENTS
$q = file_get_contents($filename);
foreach ($this->dataArray as $key => $value)
{
$q = str_replace('['.$key.']', $value, $q);
}
return $q;
So once that loop is over filling in the proper data, I need to do another search and replace for any variables left using, [FIRSTNAME]
I hope this makes sense any someone can steer me in the right direction.
Cheers
It sounds like you just want to add a line like:
$q = preg_replace('/\[[^\]]*\]/', '' , $q);
After all your defined substitutions, to eliminate any remaining square-bracketed words.
If you want to be concise, you can replace the whole function with a variation of the "one line template engine" at http://www.webmasterworld.com/php/3444822.htm, with square brackets instead of curlies.
You can actually pass arrays into the str_replace function as arguments.
$keys = array(
'FIRSTNAME',
'LASTNAME'
):
$replacements = array(
'George',
'Smith'
);
str_replace($keys, $replacements, $input);
And if you want to remove first name if its blank, why don't you just add it to the key => replacement array with a value of ''
?
$this->dataArray['FIRSTNAME'] = '';
or something like
if (!isset($this->dataArray['FIRSTNAME'])) {
$this->dataArray['FIRSTNAME'] = '';
}
精彩评论