喜欢搜索每个逗号分隔值的前三个字符

In a string,

$string_example = "cats, dogs, horses"

I'd like to get

$string_truncated = "cat, dog, hor"

i.e. getting the first three characters of each comma separated value

Later, I will use this in an SQL LIKE statement to restrict search results that match at least the first three characters given (I can't do FULL TEXT because I want to keep my foreign key constraints and can't give up my DB engine)

$string_example = "cats, dogs, horses";
$arr = explode(',',$string_example);
$newArr = array();
foreach($arr as $val){
  if($val != ''){
     $newArr[] = substr(trim($val),0,3); 
  }
}
$newStr = implode(', ',$newArr);
echo $newStr;

You can do:

<?php
$string_example = "cats, dogs, horses";
$arr = explode(",", $string_example);
$newArr = array();
foreach($arr as $value) $newArr[] = substr(trim($value), 0, 3);
$newString = implode($newArr,", ");
echo $newString;
?>

Output:

cat, dog, hor

Using array_map, substr, explode and implode:

$string_example = "cats, dogs, horses"

$truncated_ary = array_map(
                    function($search_string){
                       return substr($search_string, 0, 3)
                    }, 
                    explode(',', $string_example)
                 );

$string_truncated = implode(',', $truncated_ary);
$string_example = "cats, dogs, horses";
$words = explode(',',$string_example);
$result = array();
foreach($words as $val){
  if($val != ''){
     $result[] = substr(trim($val),0,3); 
  }
}
$newStr = implode(', ',$result);
echo $newStr;