PHP Cut String At specific character

2020-08-18 05:54发布

$string = "aaa, bbb, ccc, ddd, eee, fff";

I would like to cut string after third , so i would like to get output from string:

aaa, bbb, ccc

标签: php character
6条回答
Bombasti
2楼-- · 2020-08-18 05:56

If you don't know exactly the number chars to count I would suggest an Implode Explode like this:

$string = "aaa, bbb, ccc, ddd, eee, fff";
$arr = explode(',' , $string);
$out = array();
for($i = 0; $i < 3; $i++)
{
  $out[] = $arr[$i];
}
$string2 = implode(',', $out);
echo $string2; // output is: aaa, bbb, ccc

Update

here's a phpfiddle

查看更多
倾城 Initia
3楼-- · 2020-08-18 05:56
$string = "aaa, bbb, ccc, ddd, eee, fff";
$arr = explode(", ", $string);
$arr = array_splice($arr, 0, 3);
$string = implode($arr, ", ");

echo $string; // = "aaa, bbb, ccc"
查看更多
太酷不给撩
4楼-- · 2020-08-18 06:07

If it is specific for uptill third string than try,

$output = implode(array_slice(explode(",",$string), 0, 3),","); 

Demo.

查看更多
做自己的国王
5楼-- · 2020-08-18 06:14
$x = explode(',', $string);
$result = "$x[0], $x[1], $x[2]";
查看更多
姐就是有狂的资本
6楼-- · 2020-08-18 06:16

You can use strpos() and substr() for this. See

Alternate approach using explode:

$arr = explode(',', $string);
$string = implode(',',array_slice($arr, 0, 3);
查看更多
Bombasti
7楼-- · 2020-08-18 06:18

You can use explode() and implode() PHP functions to get it.

查看更多
登录 后发表回答