PHP - 从数据库连接字符串

时间:2013-05-14 13:27:44

标签: php codeigniter concatenation

我有字符串发送电子邮件注册。 该字符串存储在数据库中。

当我用我的模型加载字符串时。

//string from db
Hi {$email} , bla bla bla

我的控制器示例。

  some function (){
      $text = $this->Some_model->get_string();

      // this var get from post
      $email = 'foo@mail.com'
      echo $text;
  }

并且字符串中没有任何变化。 使用str_replace我不能得到这样的输出。

您好foo@mail.com,bla bla bla

如果我的情况怎么办?我有两个或更多的字符串要替换?

例如

 Hi {$email}, this is your {$username}

4 个答案:

答案 0 :(得分:1)

如果每个字符串包含可以执行的代码,PHP就不会神奇地检查它们。如果数据库中的字符串实际上包含Hi {$email} , bla bla bla,那么PHP将保留它。

因此,您需要手动覆盖字符串中的值以匹配实际值。最安全的方法是简单的str_replace

<?php
$string = 'Hi {$email} , bla bla bla';
$email = 'foo@example.com';
$output = str_replace('{$email}', $email, $string);
$output = str_replace('{$username}', $username, $output );
echo $output;
//Hi foo@example.com , bla bla bla
?>

或在您的代码中

<?php
some function (){
    $text = $this->Some_model->get_string();
    $email = 'foo@mail.com';
    echo str_replace('{$username}', $username, str_replace('{$email}', $email, $text));
   //Hi foo@mail.com , bla bla bla
}
?>

如果在放入数据库之前创建字符串(带双引号),{$email}的值将会更改

<?php
$email = 'foo@mail.com';
$text = "Hi {$email} , bla bla bla"; //notice the double quotes, single qoutes wont work
echo $text;
//Hi foo@mail.com , bla bla bla
?>

答案 1 :(得分:0)

你的功能应该是这样的,假设你有像'test'这样的字符串

function get_email_string(){
      $text = $this->Some_model->get_string();
      $email = '@mail.com'
      echo $text.$email;
}

输出

test@mail.com

答案 2 :(得分:0)

这种方式不正确......你可以这样做。

function emailString(){
  $text = "Hi __EMAIL__  , bla bla bla";

   $text = str_replace('__EMAIL__','foo@mail.com');
  echo $text;

}

答案 3 :(得分:0)

我认为您的$textHi {$email} , bla bla bla,因为您写了//string from db,您可以使用str_replace来获得所需的输出

$email = 'foo@mail.com'
echo str_replace('{$email}', $email, $text);

这将结束

Hi foo@mail.com , bla bla bla
相关问题