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


PHP string replacement operations with DB in consideration

我想使用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)

提前感谢!

$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"
<?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'];
?>

如果你想使用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;