note 97235 modified in function.trim by danbrown
| From: | danbrown@php.net | Date: | Fri, 09 Apr 2010 13:09:35 +0000 |
| Subject: | note 97235 modified in function.trim by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-168073@lists.php.net to get a copy of this message | ||
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"
?>
--was--
<?php
// 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()
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"
?>
http://php.net/manual/en/function.trim.php