Search for [ ] and replace everything between it

℡╲_俬逩灬. 提交于 2019-12-11 07:01:43

问题


I have a template file that uses the structure [FIRSTNAME] [LASTNAME]

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


回答1:


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.




回答2:


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'] = '';
}


来源:https://stackoverflow.com/questions/6473945/search-for-and-replace-everything-between-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!