Skip to content

Instantly share code, notes, and snippets.

@Cxarli
Created April 27, 2016 19:42
Show Gist options
  • Save Cxarli/fe30cfdc2135d2a2e8b6824f3b4e437b to your computer and use it in GitHub Desktop.
Save Cxarli/fe30cfdc2135d2a2e8b6824f3b4e437b to your computer and use it in GitHub Desktop.
A PHP framework for making it easier to do common string functions
<?php
class StringPlus {
public $str = '';
public function __construct($string) {
// Convert booleans
if ( $string === true ) {
$this->str = "true";
} else if ($string === false) {
$this->str = "false";
} else {
$this->str = strval($string);
}
}
public function __toString() {
return $this->str;
}
public function startsWith($needle, $ignoreCase=false) {
$haystack = $this;
$needle = new StringPlus($needle);
if($ignoreCase) {
$haystack = $this->lowercase();
$needle = $needle->lowercase();
}
return substr(strval($haystack), 0, $needle->length()) == strval($needle);
}
public function endsWith($needle, $ignoreCase=false) {
$haystack = $this;
$needle = new StringPlus($needle);
if ( $ignoreCase ) {
$haystack = $this->lowercase();
$needle = $needle->lowercase();
}
return substr(strval($haystack), -$needle->length()) == strval($needle);
}
public function contains($needle, $ignoreCase=false) {
$haystack = $this;
$needle = new StringPlus($needle);
if ( $ignoreCase ) {
$haystack = $this->lowercase();
$needle = $needle->lowercase();
}
return strpos(strval($haystack), strval($needle)) !== false;
}
public function test($regex) {
return preg_match($regex, $this->str) === 1;
}
public function uppercase() {
return new StringPlus(strtoupper($this->str));
}
public function lowercase() {
return new StringPlus(strtolower($this->str));
}
public function length() {
return strlen($this->str);
}
}
?>
@Cxarli
Copy link
Author

Cxarli commented Apr 27, 2016

Do whatever the f=== you want with it, whatever personal or commercial, make a million dollars with it, I don't care. It was fun making it, and I hope it can be useful to anyone.

Tests/Usage: https://gist.github.com/C-Bouthoorn/cde2001f3daf6ffadf16e5d0c937681a

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment