如何使用静态值动态替换产品名称

时间:2014-07-24 14:47:36

标签: php mysql arrays string replace

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

例如

" Zon Stock"是从数据库中提取的产品名称,我希望系统仅替换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);        

1 个答案:

答案 0 :(得分:0)

试试这个而不是......

$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;
}

可能这对你有帮助。