Quick PHP Functions : str_remove

I had a need for a simple function to remove a portion of a string similar to how it is done with most
functions in string libraries such as .NET’s String.Remove.

Using the function is as simple as

$str = str_remove($str, 10, 2);

and here is the implementation.

if(!function_exists('str_remove')) {
	function str_remove($str, $startOffset, $length) {
		$endPos = ($startOffset + $length);
		$strLeft = substr($str, 0, $startOffset);
		$strRight = substr($str, $endPos, strlen($str) - $length);
		$newStr = $strLeft . $strRight;
		return $newStr;

You could also shorten this a couple of lines by using substr_replace.

if(!function_exists('str_remove')) {
	function str_remove($str, $startOffset, $length) {
		$newStr = substr_replace($str, "", $startOffset, $length);
		return $newStr;


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s