PHP Cut String At specific character

2020-08-18 06:01发布

问题:

$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

回答1:

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

  • http://php.net/strpos
  • http://php.net/substr

    $string = substr($string, 0, strpos($string, ', ddd'));

Alternate approach using explode:

$arr = explode(',', $string);
$string = implode(',',array_slice($arr, 0, 3);


回答2:

$x = explode(',', $string);
$result = "$x[0], $x[1], $x[2]";


回答3:

If it is specific for uptill third string than try,

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

Demo.



回答4:

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



回答5:

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



回答6:

$string = "aaa, bbb, ccc, ddd, eee, fff";
$arr = explode(", ", $string);
$arr = array_splice($arr, 0, 3);
$string = implode($arr, ", ");

echo $string; // = "aaa, bbb, ccc"


标签: php character