Created
June 1, 2011 14:34
-
-
Save rowanmanning/1002408 to your computer and use it in GitHub Desktop.
Concept for a PHP String class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//============================================================ | |
// CONSTANTS | |
// direction (for strpos etc) | |
String::FORWARD; | |
String::REVERSE; | |
// case | |
String::CASE_LOWER; | |
String::CASE_UPPER; | |
String::CASE_TITLE; | |
String::CASE_SENTENCE; | |
// position (for trim, pad etc) | |
String::POSITION_RIGHT; | |
String::POSITION_LEFT; | |
String::POSITION_BOTH; | |
//============================================================ | |
// METHODS | |
// define | |
$str = new String('Example'); | |
// or | |
$str = string('Example'); | |
// case changes | |
$str->case(String::CASE_LOWER); // String('example') | |
// get a substring | |
$str->part(2, 3); // String('amp') | |
// get position of a substring | |
$str->position_of('a', String::FORWARD); // Integer(2) | |
// split a string | |
$str->split('m'); // Array('Exa', 'ple') (also second argument is max number of chunks to return) | |
// return the character at a position | |
$str->character(0); // String('E') | |
// get the string length | |
$str->length(); // Integer(7) | |
// trim characters from a string | |
$str->trim('e', String::POSITION_BOTH); // String('xampl') | |
// pad a string | |
$str->pad(10, '-', String::POSITION_RIGHT); // String('Example---') | |
// perform a replacement | |
$str->replace('Ex', 'S'); // String('Sample') | |
// ..etc | |
//============================================================ | |
// CHAINING | |
// 'Example' to 'examples' | |
$str = string('Example') | |
->case(String::CASE_LOWER) | |
->pad(8, 's') | |
; | |
// if Integer/Array classes etc. were created... | |
// 'Hello World!' to 'World, Hello'. | |
$str = string('Hello World!') | |
->split(' ') // now an array | |
->reverse() | |
->join(' ') // now a string again | |
->replace('!', ',') | |
; | |
//============================================================ | |
?> |
I can see it being useful to have up your sleeve - esp when writing little apps that chug away at large amounts of data (e.g. parsing/cleansing CSV files) – have you done any comparisons against native string manipulation yet to see how it fares? If the cost/benefit (speed of execution vs speed of coding) balances, could be onto a good un!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is this ridiculous? Am I over-thinking? Would this cause your scripts to grind to an appallingly slow speed? I'm genuinely interested – I think it'd speed up the way I work and make my code more readable... What are your thoughts?