我已经在谷歌上搜索过,但是,我仍然无法找到解决我的数组问题的最佳解决方案。
预期:
1. 用户将字符串发布到服务器 ->
2.我们过滤字符串并替换那些与数据库中存储的数据匹配的单词->
3 将已被我们替换的字符串插入数据库。
当前完成:
1. 具有名为
(1)ID (2)alias (3)replacement
的列的数据表2. 一个表单,允许用户发布字符串
(post by jquery-ajax)
3. 一个函数返回数组中表的所有结果
在不读取 DB 结果的情况下测试此类:
类
class replace{ function tag($_input){ $definition = array('morning' => 'Good morning!', 'nowTime' => time()); foreach ($definition as $key => $value) $_input= str_replace('{{' . $key . '}}', $value, $_input); return $_input;` } }
使用方法
$replace= new replace(); $_input = '{{morning}} everyone, current unix time is {{nowTime}}' ; echo $replace->tag($_input);
输出结果(成功(
大家早上好,当前的 unix 时间1417758157
但是,当我尝试使用数据库输出的数组来替换$definition
问题发生:
数据库的数组输出
数组
0 => array 'ID' => 445 'alias' => 'morning' 'replacement' => 'Good morning' 1 => array 'ID' => 446 'alias' => 'nowTime' 'replacement' => time() 2 => array 'ID' => 447 'alias' => 'tommorowNow' 'replacement' => time()+86400
试
function replace(){ // $tagEngine is the array ouput from Db foreach ($tagEngine as $arrKey) { $definition = array($arrKey['alias'] => $arrKey['replacement']); return ($definition); }; }
但只返回第一个结果
数组
'morning' => 'Good morning'
此外,我想问一下如何完成我首先提到的预期结果。我很困惑把str_replace放在$replace()
的什么地方.
谢谢!
在我看来,
有些事情需要改变。首先,使用类中的定义,而不是单独使用(否则你只是使用类来存储函数而不是它的"对象"属性(;
class replace {
public $definitions;
public function setDefinitions($definitions) {
$this->definitions = $definitions;
}
public function tag($input) {
if($this->definitions && is_array($this->definitions)) {
foreach ($this->definitions as $definition) {
if($defintion['alias'] == 'time') {
$input = str_replace('{{' . $definition['alias'] . '}}', date('Y-m-d'), $input);
} else {
$input = str_replace('{{' . $definition['alias'] . '}}', $definition['replacement'], $input);
}
}
}
return $input;
}
}
如上所示,您可以将数据库中的定义存储在对象中,并在tag()
public 方法中使用它们。
其次,不要使用函数,只需在需要的位置调用字符串解析即可。这样:
$replace = new replace();
$replace->setDefinitions($tagEngine);
$parsedString = $replace->tag('{{morning}} everyone, current unix time is {{nowTime}}');
echo $parsedString;
我还没有测试代码(所以我希望我没有犯任何错误(。