$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
$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
You can use strpos()
and substr()
for this. See
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);
$x = explode(',', $string);
$result = "$x[0], $x[1], $x[2]";
If it is specific for uptill third string than try,
$output = implode(array_slice(explode(",",$string), 0, 3),",");
Demo.
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
here's a phpfiddle
You can use explode() and implode() PHP functions to get it.
$string = "aaa, bbb, ccc, ddd, eee, fff";
$arr = explode(", ", $string);
$arr = array_splice($arr, 0, 3);
$string = implode($arr, ", ");
echo $string; // = "aaa, bbb, ccc"