【问题标题】:How to update/delete a single word in a line of text如何更新/删除一行文本中的单个单词
【发布时间】:2012-06-18 08:04:16
【问题描述】:

我有一个小问题需要你的帮助。如何更新以逗号分隔的部分文本组。当文本输入数据库时​​,它是一行文本,每个单词之间有逗号,但是当我想将它回显时,我使用explode函数将它们分成单独的单词,而不是像我这样的单行文本它在数据库中。

所以我现在的问题是,如何对数据库中的单个单词进行更新/删除。请记住,我将它作为数据库中的单行文本,我对更新整行文本不感兴趣......只是文本中的一个单词..

谢谢。

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

【问题讨论】:

  • 是否可以将数据库更改为将这些标签(或其他标签)放在数据库中的单独行中,然后使用WHERE 子句选择所有标签?跨度>

标签: php mysql str-replace explode


【解决方案1】:

可以在sql更新查询中使用replace()函数。

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

【讨论】:

  • 不过,这会将 'last_page_visited' 替换为 'last_pnewstring_visited'
  • 如何在 WHERE 文本中添加 REGEXP '[[:<:>:]]'
  • 错字:应该是 WHERE text REGEXP '[[:<:>:]]'
  • 即使它匹配(我认为它不匹配)它仍然会将var_one,age,var_two,last_page_visited,var_three 变成var_one,newstring,var_two,lastpnewstring_visited,var_three。我认为可行的正则表达式如下:(^age,|,age$|,age,|^age$),但是据我所知,MySQL 没有使用正则表达式的替换功能,唯一的解决方法是使用如下 UDF:launchpad.net/mysql-udf-regexp跨度>
  • 我正在使用 mysql 5.5 和 mysql 工作台,我可以运行上述查询。
【解决方案2】:

更新或删除数组中的单词,然后分解数组并将新值保存到数据库字段。

//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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-10
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 2014-11-11
    相关资源
    最近更新 更多