2013-12-17 43 views
2

在一個字符串的前三個字母,喜歡搜索每個逗號分隔值

$string_example = "cats, dogs, horses" 

我想獲得

$string_truncated = "cat, dog, hor" 

即讓每一個逗號分隔值的前三個字符

後來,我將使用這一個SQL LIKE語句來限制給出至少前三個字符匹配的搜索結果(因爲我要保持我的外國我不能這樣做全文鍵約束和不能放棄我的數據庫引擎)

回答

2
$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; 
1

你可以這樣做:

<?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; 
?> 

輸出:

cat, dog, hor 
0

使用array_mapsubstrexplodeimplode

$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); 
0
$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;