从字符串中删除最后一个字符。

3

我有一个国家列表作为数组..我希望按照以下格式将此数组转换后通过ajax返回:

"印度","美国","英国" ..

使用以下代码可以获得我要找的结果:

foreach($country_list as $country) {
   $countries .= '"'.$country['label'].'",';
}

问题在于它输出的结果是像“印度”,“美国”,“英国”等,即带有逗号。尝试使用以下方法去除逗号:
substr_replace($countries, "0", -1);

并且

rtrim($countries, ",");

但是没有起作用!...请帮忙!


1
为什么不使用implode函数?它恰好做你所需的,并且还能删除尾随的“逗号”。 - zewa666
https://dev59.com/Ym035IYBdhLWcg3wJcnT?rq=1 - DevlshOne
@zewa666 这是一个关联数组:$country['label'] - insertusernamehere
$countries 是数组还是字符串? - Tushar Gupta - curioustushar
rtrim应该可以工作的! - Sven
9个回答

8
我认为您在修剪后遗漏了将变量重新分配的步骤:
$s = '"india","usa","uk",';
$s = rtrim($s, ',');
// prints "india","usa","uk"
print $s;

Demo

Try before buy


6

可以尝试使用substr()或者mb_substr()

substr($string, 0, -1);
mb_substr($string, 0, -1);

or check this link


请查看此链接:https://dev59.com/Ym035IYBdhLWcg3wJcnT - Haseeb

1

你尝试过使用:str_replace(",", " ", $countries);

这个函数应该会将每个逗号替换成一个空格。


为什么要用空格替换? - Sven
1
我不希望字符串末尾只有逗号。也不想省略其中的所有逗号。 - Prince Singh

1
if (strlen($b) > 1){
   $b = substr($b,0, -1);
}

0

使用implode代替:

$arr = array();
foreach($country_list as $country)
  array_push($arr, $country['label']);
$comma_separated = implode(",", $arr);

这个输出看起来像是印度、美国、英国,我需要的是“印度”,“美国”,“英国”。谢谢。 - Prince Singh

0

试试这个

$countries = [];
foreach($country_list as $country) {
   $countries[] = $country['label'];
}
$new_array = implode(",", $countries);

0

请尝试以下方法:

  1. 创建一个变量($comsep)并将其初始化为空字符串。
  2. 在foreach循环中,在字符串开头连接变量($comsep)。
  3. 在连接语句之后,在foreach循环中添加一条额外的语句,将变量($comsep)设置为值“,”。

这将在每个附加的字符串开头放置一个逗号,除了第一个字符串。不再有尾随逗号需要处理,因此无需尝试将其修剪掉。


0

// 尝试在php中使用chop()函数。它有助于从字符串中删除最后一个字符

<?php
    echo '<br>' .$country_name = "'USA','UK','India',";
    echo '<br>' .chop($country_name,",");
    exit;
?>

输出:'美国','英国','印度'


-1
foreach($country_list as $country) {
   $countries[] = $country['label'];
}
json_encode($countries); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接