$string = "aaa, bbb, ccc, ddd, eee, fff";
I want to cut the string after the third, so I would like to get output from the string:
aaa, bbb, ccc
You can use strpos() and substr() for this. Cm.
strpos()
substr()
http://php.net/substr
$string = substr($string, 0, strpos($string, ', ddd'));
Alternative blast approach:
$arr = explode(',', $string); $string = implode(',',array_slice($arr, 0, 3);
$x = explode(',', $string); $result = "$x[0], $x[1], $x[2]";
If you do not know the exact number of characters to count, I would suggest Implode Explode as follows:
Implode
Explode
$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 phpfiddle
You can use the explode () and implode () functions of PHP to get it.
If it is given for the third line than try,
$output = implode(array_slice(explode(",",$string), 0, 3),",");
Demo
$string = "aaa, bbb, ccc, ddd, eee, fff"; $arr = explode(", ", $string); $arr = array_splice($arr, 0, 3); $string = implode($arr, ", "); echo $string; // = "aaa, bbb, ccc"