我如何用静态值动态替换产品名称,即从数据库中获取所有产品名称,但我想创建从数据库中提取所有记录后将替换产品名称中某些单词的函数。

例如

“区域库存”是从数据库中获取的产品名称,我希望系统仅替换Stock,而不应该替换Zon Stock完成的产品名称

问题

问题是我的代码工作正常,但仅使用硬代码而不使用动态记录

静态码

$a="this is testing script STOCK,stock,Stock";

$replaceWord=array("

STOCK " =>  "UAE PRODUCTS",
"stock" => "uae products",
"Stock" => "Uae Products");

$new_test= strtr($a, $replaceWord);

echo $new_test;


但是相同的代码不适用于从数据库中获取的product name field

$query=mysql_query("select pnames from products order by pid asc");

while($row=mysql_fetch_array($query))
{

$a = $row['pnames'];

$replaceWord=array("

STOCK " =>  "UAE PRODUCTS",
"stock" => "uae products",
"Stock" => "Uae Products");

$new_test= strtr($a, $replaceWord);

echo $new_test;


}


谢谢,我已经在这里完成了我的脚本

here my script

$query=mysql_query("select pnames from products order by pid asc");
$row=mysql_fetch_array($query);

$a=$row['pnames'];

$replaceWord=array(
$a="STOCK" =>  "UAE DUBAI",
$a="stock" => "uae dubai",
$a="Stock" => "Uae Dubai");

echo $new_row['Name'] =     strtr($row['pnames'], $replaceWord);

最佳答案

试试这个代替...

$query = mysql_query("select pnames from products order by pid asc");

while($row=mysql_fetch_array($query)) {

  $a = $row['pnames'];

  // for simplicity I'm using function here
  $get_result = word_replace($a);

}

function word_replace($key) {

 // array of static words
 $replaceWord = array(
  "STOCK " =>  "UAE PRODUCTS",
  "stock" => "uae products",
  "Stock" => "Uae Products"
 );

 // Find in array
 if (array_key_exists($key, $replaceWord)) {

  // replace that string
  $replace_string = $replaceWord[$key];

 } else {
  $replace_string = $key;
 }
 return $replace_string;
}


可能对您有帮助。

关于php - 我如何用静态值动态替换产品名称,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24936976/

10-11 12:44