note 94811 added to function.ucwords
| From: | mariodivece at yahoo dot com | Date: | Thu, 26 Nov 2009 05:04:15 +0000 |
| Subject: | note 94811 added to function.ucwords | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-163295@lists.php.net to get a copy of this message | ||
Here's a simple function to convert a pascal cased, camel cased or underscore-separated string
(usually for identifiers) that works well. It'd be nice if someone could provide the regex
equivalent.
<?php
class StringHelper
{
const CONVENTION_AUTO = 0;
const CONVENTION_PASCAL = 1;
const CONVENTION_CAMEL = 2;
const CONVENTION_USCORE = 3;
/**
* Converts a camel-cased, pascal-cased or underscore-separated word into a human-readable
string
* @param string $str
* @param int $convention
* @return string
*/
public static function toWords($str, $convention = self::CONVENTION_AUTO)
{
if ($convention === self::CONVENTION_AUTO)
{
if (self::strContains($str, '_'))
{
$convention = self::CONVENTION_USCORE;
}
else
{
$convention = self::CONVENTION_PASCAL;
}
}
if ($convention === self::CONVENTION_USCORE)
{
return str_replace('_', ' ', $str);
}
if ($convention === self::CONVENTION_PASCAL || $convention === self::CONVENTION_CAMEL)
{
$baseStr = ucfirst($str);
$whitespaceBefore = strtoupper($str) . "01234567890";
$retStr = "";
for ($i = 0; $i < strlen($baseStr); $i++)
{
$chr = $baseStr[$i];
if (strstr($whitespaceBefore, $chr) !== false)
{
$retStr .= " " . $chr;
}
else
{
$retStr .= $chr;
}
}
return trim($retStr);
}
else
{
throw new Exception(692, '$convention must be one of the CONVENTION-prefixed
constants');
}
}
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 189.169.159.79
----
Manual Page -- http://www.php.net/manual/en/function.ucwords.php
Edit -- https://master.php.net/note/edit/94811
Del: integrated -- https://master.php.net/note/delete/94811/integrated
Del: useless -- https://master.php.net/note/delete/94811/useless
Del: bad code -- https://master.php.net/note/delete/94811/bad+code
Del: spam -- https://master.php.net/note/delete/94811/spam
Del: non-english -- https://master.php.net/note/delete/94811/non-english
Del: in docs -- https://master.php.net/note/delete/94811/in+docs
Del: other reasons-- https://master.php.net/note/delete/94811
Reject -- https://master.php.net/note/reject/94811
Search -- https://master.php.net/manage/user-notes.php