考虑使用DB的PHP字符串替换操作

时间:2013-02-22 12:10:55

标签: php database string preg-replace

我希望使用DB在PHP中对我的字符串执行一些替换类型的操作。 例如:

$inputString = "My name is [[name-abc]] and age [[age-25]]";

我有DB表如下:

id    input        output
 1     name-abc    LINK_TO_ABC_PROFILE
 2     name-def    LINK_TO_DEF_PROFILE
 3     age-18      LINK_TO_AGE_18
 4     age-25      LINK_TO_AGE_25

我需要输出:

$outputString = "My name is LINK_TO_ABC_PROFILE and age LINK_TO_AGE_25";

我用preg_replace尝试了各种各样的东西,但没有得到结果。任何人都可以为我编写函数,假设DB在我的数组中,如下所示:

array('name-abc' => LINK_TO_ABC_PROFILE, 'name-def' => LINK_TO_DEF_PROFILE .... 'age-25' => LINK_TO_AGE_25)

提前致谢!

3 个答案:

答案 0 :(得分:0)

<?php
$details = array('name-abc' => LINK_TO_ABC_PROFILE, 'name-def' => LINK_TO_DEF_PROFILE .... 'age-25' => LINK_TO_AGE_25);

$outputString = "My name is ".$details['name-abc']." and age ".$details['age-25'];
?>

答案 1 :(得分:0)

$inputString = "My name is [[name-abc]] and age [[age-25]]";
$replace = array('name-abc' => LINK_TO_ABC_PROFILE, 'name-def' => LINK_TO_DEF_PROFILE , 'age-25' => LINK_TO_AGE_25);
$keys = array();
foreach ($replace as $k => $v) {
    $keys[] = '[[' . $k . ']]';
}
$out = str_replace ( $keys ,  array_values($replace) , $inputString );

var_dump(($out));

输出:

string(53) "My name is LINK_TO_ABC_PROFILE and age LINK_TO_AGE_25"

答案 2 :(得分:0)

如果你想使用preg_replace,你必须构建两个单维数组而不是关联数组,尝试如下,

$input_arr = array();
$output_arr = array();
$query = "SELECT input,output FROM replacestrtbl";
$stmt = $mysqli->prepare($query);

if($stmt){
  $stmt->execute();
  $stmt->bind_result($input, $output);
  $i=0;
  while($res = $stmt->fetch()){
  $input_arr[$i] = '/\[\['.$input.'\]\]/';
  $output_arr[$i] = $output;
  $i++;
  }
  $stmt->close();
}

$inputString = "My name is [[name-abc]] and age [[age-25]]";

$output_string=preg_replace($input_arr,$output_arr,$inputString);

echo $output_string;