note 97235 deleted from function.trim by hholzgra
| From: | hholzgra@php.net | Date: | Thu, 02 Aug 2012 12:31:14 +0000 |
| Subject: | note 97235 deleted from function.trim by hholzgra | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-189673@lists.php.net to get a copy of this message | ||
Note Submitter: james [at] bandit -dot- co -dot- nz
----
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"
?>