2012-02-24 2 views
0

PHP를 사용하여 단어가없는 쉼표 , 뒤에 공백을 제거하려면 어떻게해야합니까?PHP를 사용하여 사용자가 쉼표를 입력 한 후 공백을 제거하는 방법

여기에 항목이 있습니다.

apple pie,  cherry ,   ,  pears,  crumb cake  ,   , 

그리고 지금까지 내가 얻은 바가 있습니다.

apple pie, cherry, , pears, crumb cake, 

그리고 원하는 출력이 있습니다.

apple pie, cherry, pears, crumb cake 

그리고 여기까지 내가 얻은 PHP 코드가 있습니다.

$words = preg_split('/,/', filter_var($words, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES), -1, PREG_SPLIT_NO_EMPTY); 
$words = preg_replace('/\s+/', ' ', $words); 
$words = array_map('trim', $words) 
+0

XPX는 WPSE는 워드 프레스 구체적인 질문입니다. 이것은 순전히 스택 오버 플로우에 더 적합한 PHP 게시물입니다. 이 질문은 사회자에 의해서도 마이그레이션 될 수 있습니다. –

+0

스택 오버플로로 마이그레이션. – EAMann

답변

0

나는이 특히 워드 프레스 문제라고 생각하지 않습니다,하지만 당신은 쉼표로 배열로 폭발하여 데이터를 살균하고 트림/빈 값을 제거 할 수 있습니다.

$words = 'apple pie, , cherry, pears, ,'; 
$words_array = explode(',', $words); 
$clean_words_array = array(); 
foreach($words_array as $word) { 
    if (!empty(trim($word))) { 
     $clean_words_array[] = trim($word); 
    } 
} 

// you now have an array with words 
// you can put them back in a comma separated string 
// using the implode() function if you want 
5

하나 개 라이너 재미 :

$words = array_filter(array_map('trim',explode(',',$words))) 
+0

게시하려고했습니다. 콜백이없는'array_filter'는 내가 만났던 가장 유용한 PHP 속임수 중 하나입니다. – goldenapples

관련 문제