2015년 10월 21일 수요일

[PHP] trim()

james [at] bandit -dot- co -dot- nz
09-Apr-2010 11:29

Trims occurances of every word in an array from the beginning and end of a string + whitespace and optionally extra single characters as per normal trim()


<?php 
function trim_words($what, $words, $char_list = '') { 
    if(!is_array($words)) return false; 
    $char_list .= " \t\n\r\0\x0B"; // default trim chars 
    $pattern = "(".implode("|", array_map('preg_quote', $words)).")\b"; 
    $str = trim(preg_replace('~'.$pattern.'$~i', '', preg_replace('~^'.$pattern.'~i', '',trim($what, $char_list))), $char_list); 
    return $str; 
} 

// for example: 
$trim_list = array('AND', 'OR'); 

$what = ' OR x = 1 AND b = 2 AND '; 
print_r(trim_words($what, $trim_list)); // => "x = 1 AND b = 2" 

$what = ' ORDER BY x DESC, b ASC, '; 
print_r(trim_words($what, $trim_list, ',')); // => "ORDER BY x DESC, b ASC" 
?>

댓글 없음:

댓글 쓰기