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

问题描述 投票:0回答:4

这是我的字符串:

$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 string comma
4个回答
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

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
投票

试试这个

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

0
投票

如果$codes是一个字符串,你可以使用qzxswpoi正则表达式:

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

正则表达式的解释:

第一捕获组(_ \ 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); 匹配字符_字面意思(区分大小写)
  • _匹配一个数字(等于[0-9])
  • \d Quantifier - 尽可能多次匹配一次和无限次,根据需要回馈(贪婪)
© www.soinside.com 2019 - 2024. All rights reserved.