1

我是 PHP 新手

我想删除字符串的最后一个逗号,我该怎么做。这是我的代码:

<?php
$sub ="economic,maths,science";
$cap = explode(",",$sub);
foreach($cap as $new){
    echo ucfirst($new).",";
    }
?>

任何帮助将不胜感激,在此先感谢。

4

7 回答 7

2

简单的修剪就足够了:

$string = trim($string, " ,");

请注意, trim() 函数的第二个参数允许您从字符串中修剪定义的字符,而不仅仅是空格。因此,在我的用法中定义了两个字符:空格字符“”和逗号“,”。

如果您想在没有循环的情况下将单词大写:

$string = ucwords(trim($string, " ,"));

注意:由于 ucwords() 函数会查找空格来定义单词边界,因此“apple,apple”不起作用但“apple,apple”会起作用,所以:

$string = ucwords(str_replace(array(","," "),array(", "," "),trim($string, " ,")));

is the best solution. (There are two spaces in the second element of first replacement array.)

于 2012-04-30T00:26:58.963 回答
1
<?php
$sub ="economic,maths,science";
$cap = explode(",",$sub);
$cap2 = array();
foreach($cap as $new){
    $cap2[] = ucfirst($new);
}
echo implode(",",$cap2)
?>
于 2012-04-29T14:22:51.587 回答
1
$sub ="economic,maths,science";
var_dump(implode(',', array_map('ucfirst', explode(",", $sub))));
于 2012-04-29T14:24:40.677 回答
0

这个适用于单词边界,而不仅仅是逗号:

preg_replace('~\b(\w+)\b~e', 'ucfirst("\\1")', "economic,maths,science");
于 2012-04-29T14:25:41.607 回答
-1

您可以在没有这样的循环的情况下执行此操作:

$string = 'test, test, test';
$pos = strrpos($string, ',');

$string[$pos] = '';

echo $string;
于 2012-04-29T14:22:59.407 回答
-1

一个简单的正则表达式可以:

preg_replace('/,([^,])$/','\1',$str);
于 2012-04-29T14:23:18.003 回答
-2
<?php 
$sub = "economic,maths,science";
$cap = explode(",",$sub);
$count = count($cap);
$i = 1;     
foreach($cap as $newSub){
    if($count>$i){
        echo ucfirst($newSub).",";
    }else{
        echo ucfirst($newSub);
    }
    $i++;
}   
?>
于 2012-04-29T14:20:46.773 回答