搜索[]并替换它之间的所有内容 [英] Search for [ ] and replace everything between it
问题描述
我有一个使用结构
[FIRSTNAME]
[LASTNAME]
等等的模板文件....我会正在进行搜索并替换它。我想要做的一件事是,当模板被发回时,如果我没有规定,[FIRSTNAME] ....它仍然显示在模板中...我想使它成为空如果我避难'$ t
$ b
在我的代码中我使用FILE_GET_CONTENTS
$ q = file_get_contents($ filename);
foreach($ this-> dataArray as $ key => $ value)
{
$ q = str_replace('['。$ key。']',$ value,$ q);
}
return $ q;
因此,一旦循环结束填写正确的数据,我需要再次搜索并替换任何使用的变量,[FIRSTNAME]
我希望这是有道理的,任何人都可以引导我朝着正确的方向前进。
干杯
听起来就像你只想添加一行:
$ q = preg_replace('/ \ [[^ \]] * \] /','',$ q);
完成所有定义的替换后,删除任何剩余的方括号内的字词。
$ b
如果您想简明扼要,您可以用 http://www.webmasterworld.com/php/3444822.htm ,用方括号代替curlies。
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
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.
这篇关于搜索[]并替换它之间的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!