如何从逗号分隔的字符串中删除单词

时间:2015-04-04 19:11:10

标签: php

我试图让我的用户能够添加和删除列表中的项目。 列表的格式如下:item1,item2,item3每个项目用逗号分隔,但最后一项不以1结尾,第一项不以1开头。 因此,当我的用户想删除和项目例如item3时,我需要PHP删除它和之前的逗号。如果他们想删除item2我需要它也删除它和项目之前的逗号。如果用户想要删除item1我需要删除该项目及其后的逗号。

我没有使用数组,因为我将列表存储在mysql数据库中

这是我一直试图开始工作的代码。它适用于除项目1之外的每个项目,当我尝试删除item1时,它无法找到它,因为它正在查找起始逗号而不是结尾逗号。

$skills = 'item1,item2,item3,item4';
$skillToRemove = 'item1';
if(strpos($skills, $skillToRemove . ',') == 1)
    $newSkills = str_replace(',' . $skillToRemove, '', $skills);
else
    $newSkills = str_replace($skillToRemove . ',', '', $skills);
echo $newSkills;

3 个答案:

答案 0 :(得分:3)

学习使用数组

$skills = 'item1,item2,item3,item4';
$skillToRemove = 'item1'

$skillArray = explode(',', $skills);
$findSkill = array_search($skillToRemove, $skillArray);
if ($findSkill !== false)
    unset($skillArray[$findSkill];
$skills = implode(',', $skillArray);

答案 1 :(得分:2)

请不要使用字符串!将您的项目放入数组中,如果需要打印,请使用implode()。但只需将您的项目放入如下数组:

<?php

    $skills = ["item1", "item2", "item3", "item4"];
    $skillToRemove = 'item1';
    unset($skills[array_search($skillToRemove, $skills)]);

?>

如果您想打印列表,请执行以下操作:

echo implode(",", $skills);

答案 2 :(得分:0)

您可以使用preg_replace删除所选技能,trim删除任何剩余的逗号,使用此功能:

$newSkills = trim(
    preg_replace("/((?<=^)|(?<=,))\\Q$skillToRemove\\E(,|$)/", "", $skills),
    ","
);

正则表达式解释:

/                     Begin pattern
((?<=^)|(?<=,))       Begin match with start of string (^) or comma.
                      The `?<=` makes sure this is will not be replaced.
\Q                    Begin quote skill string. Any characters between \Q and \E
                      including metacharacters (e.g. '+' or '.') will be treated
                      as literals.
$skillToRemove        Match skill to remove (will be removed)
\E                    End of skill string quoting
(,|$)                 Followed by comma or end of string (will also be removed)
/                     End pattern

示例:

$skills = 'item1,item2,item3,item4';
$skillToRemove = 'item4';
$newSkills = trim(
    preg_replace("/((?<=^)|(?<=,))\\Q$skillToRemove\\E(,|$)/", "", $skills),
    ","
);
echo "Removed item4: ", $newSkills, PHP_EOL;

输出:

Removed item4: item1,item2,item3