How to update/delete a single word in a line of text

假装没事ソ 提交于 2019-12-12 07:03:39

问题


I need your help with a slight problem I have. How can I update a portion of group of text separated by comma. When the text is entered into the database, it's a single line of text with commas between each words, but when I want to echo it out I use the explode function to separate them into individual words and not a single line of text like I have it in the database.

So my question now is, how can I make an update/Delete to a single word in the database. Remeber, I have it as a single line of text in the database, and I'm not interested in updating the whole line of text...just a single word in the text..

Thanks.

$text = "name,fname,lname,class,age" ;    
$newtext = explode(",", $text) ;

回答1:


Could use the replace() function in the sql update query.

Update table SET text=REPLACE(text,'age','newstring')



回答2:


Update or remove the word from your array, then implode the array and save the new value to the database field.

//Remove all instances of $value from $array
function array_remove($array, $value) {
  return array_filter($array, function ($e) use ($value) {
      return $e != $value;
    });
}

// Add only unique values
function array_add($array, $value) {
  if (!in_array($value, $array))
    $array[] = $value;
  return $array;
}

$text = "name,fname,lname,class,age" ;
$newtext = explode(",", $text) ;
$newtext = array_remove($newtext, 'lname'); // Remove lname
$newtext = array_add($newtext, 'mail');     // Add mail
$newtext = array_add($newtext, 'class');    // Won't add it again
$newtext = implode(',', $newtext);          // name,fname,class,age,mail


来源:https://stackoverflow.com/questions/11078989/how-to-update-delete-a-single-word-in-a-line-of-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!