PHP Cut String

$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 
+7
source share
6 answers

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

Alternative blast approach:

 $arr = explode(',', $string); $string = implode(',',array_slice($arr, 0, 3); 
+16
source
 $x = explode(',', $string); $result = "$x[0], $x[1], $x[2]"; 
+7
source

If you do not know the exact number of characters to count, I would suggest Implode Explode as follows:

 $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 phpfiddle

+2
source

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

+1
source

If it is given for the third line than try,

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

Demo

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

All Articles