PHPLib/str.php

137 lines
2.8 KiB
PHP
Raw Normal View History

2013-01-31 15:24:10 -05:00
<?php
/**
* PHPLib
*
* A PHP library to wrap php functions in a standard fashion
*
* @package PHPLib
* @author Timothy J. Warren
* @copyright Copyright (c) 2013
* @link https://github.com/aviat4ion/PHPLib
* @license MIT
*/
// --------------------------------------------------------------------------
namespace PHPUtil;
/**
* Wrapper over php string functions with a consistent argument system
*/
class Str {
/**
* Original string to be modified
* @var string
*/
protected $original;
/**
* Constructor
*
* @param string $string
* @return Str
*/
public function __construct($string)
{
$this->original = $string;
}
/**
* Enable using the object as a function
*
* @param string $string
* @return $this
*/
public function __invoke($string)
{
$this->__construct($string);
return $this;
}
/**
* Output from the last method
*
* @return string
*/
public function __toString()
{
return (is_string($this->original))
? $this->original
: $this->_();
}
/**
* Return output from the last method
*
* @return mixed
*/
public function _()
{
return $this->original;
}
/**
* Formats a string according to the pattern passed to the str() function
*
* @see http://php.net/manual/function.sprintf.php
* @param array $replacements
* @return $this
*/
public function format(array $replacements)
{
// Add the pattern string as the first argument
array_unshift($replacements, $this->original);
// Return the formatted string
$this->original = call_user_func_array('sprintf', $replacements);
return $this;
}
/**
* Check whether a string matches the provided pattern
*
* @param string $pattern
* @return bool
*/
public function match($pattern)
{
return (bool) preg_match($pattern, $this->original);
}
/**
* Do a basic string replacement
*
* @see http://php.net/manual/function.str-replace.php
* @param mixed $pattern
* @param mixed $replacement
* @return $this
*/
public function replace($pattern, $replacement=NULL)
{
if (is_array($pattern) && is_null($replacement))
{
$replacement = array_values($pattern);
$pattern = array_keys($pattern);
}
$this->original = str_replace($pattern, $replacement, $this->original);
return $this;
}
/**
* String replacement via a regular expression
*
* @see http://php.net/manual/function.preg-replace.php
* @param mixed $pattern
* @param mixed $replacement
* @return $this
*/
public function reg_replace($pattern, $replacement)
{
$this->original = preg_replace($pattern, $replacement, $this->original);
return $this;
}
}
// End of str.php