删除逗号分隔的字符串php中的字符php

时间:2018-09-17 12:40:50

标签: php string comma

这是我的字符串:

$codes = 60textone_13, 120texttwo_14, 60textthree_15, 90textfour_16,

我删除了最后一个逗号,例如:

$implode_comma = implode(', ', $codes);

我正在尝试删除“ _number”,因此我希望将我的字符串设为:

$codes = 60textone, 120texttwo, 60textthree, 90textfour

我尝试使用以下方式删除“ _number”:

$variable = substr($implode_comma, 0, strpos($implode_comma, "_"));

但是它只返回第一个元素:

60textone

我该如何解决?谢谢。

4 个答案:

答案 0 :(得分:2)

此处:

<?php

$codes = '60textone_13, 120texttwo_14, 60textthree_15, 90textfour_16';

$codes = explode(', ', $codes);
$result = [];
foreach ($codes as $code) {
    $result[] = preg_replace('/(_)\w+/', '', $code);
}

var_dump($result);

?>

输出:

array(4) { [0]=> string(9) "60textone" [1]=> string(10) "120texttwo" [2]=> string(11) "60textthree" [3]=> string(10) "90textfour" }

如果您想要字符串而不是数组,则可以内嵌数组,只需在var_dump($result);之前添加此代码

$result = (implode(', ', $result)); 

答案 1 :(得分:1)

尝试

$str ="60textone_13,120texttwo_14,60textthree_15, 90textfour_16";
$codes = explode(',', $str);
foreach ($codes as $value) {
    $variable[] = substr($value, 0, strpos($value, "_"));
}
$implode_comma = implode(',',$variable);
echo $implode_comma;

答案 2 :(得分:1)

假设您的$codes是一个字符串,例如:60textone_13,120texttwo_14,60textthree_15,90textfour_16 (如果不看答案的末尾,该怎么做**)。

现在您可以像这样使用array-map

$arr = explode(",",trim($str));
function removeNum($s) {
    return substr($s, 0, -3);
}

$a = array_map("removeNum", $arr);
echo print_r($a, true);

如果数字不总是2位,请使用:

substr($s, 0, strpos($s, "_")); 

输出:

Array (
    [0] => 60textone
    [1] => 120texttwo
    [2] => 60textthree
    [3] => 90textfour
)

**如果不使用以下代码:

$codes = "60textone_13, 120texttwo_14, 60textthree_15, 90textfour_16,";
$str=preg_replace('/\s+/', '', rtrim($codes,",")); //remove spaces and last comma

答案 3 :(得分:0)

如果$codes是字符串,则可以将正则表达式与preg_replace()一起使用:

$codes = "60textone_12, 120texttwo_13, 60textthree_14, 90textfour_15";
$no_number = preg_replace('/_\d+/', '', $codes);
echo $no_number;

如果$codes是一个数组,您将遍历它们,使用preg_replace_number与正则表达式/_\d+/进行匹配:

$codes = array("60textone_13", "120texttwo_14", "60textthree_15", "90textfour_16");
 foreach($codes AS $code) {
    $new_code[] = preg_replace('/_\d+/', '', $code); 
}
echo implode(',', $new_code);

正则表达式的解释:

第一个捕获组(_ \ d +)

  • _从字面上匹配字符_(区分大小写)
  • \d匹配一个数字(等于[0-9])
  • +量词-在一次和无限次之间进行匹配,并尽可能多地匹配,并根据需要进行回馈(贪婪)