繁体   English   中英

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

[英]remove character in comma separated string php

这是我的字符串:

$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

我该如何解决? 谢谢。

这里:

<?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);之前添加这段代码var_dump($result);

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

假设您的$codes是一个字符串,如: 60textone_13,120texttwo_14,60textthree_15,90textfour_16 (如果没有,请查看答案的结尾如何做到这一点**)。

现在你可以像这样使用数组映射

$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

尝试这个

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

如果$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])
  • +量词——匹配一次和无限次,尽可能多次,根据需要回馈(贪婪)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM