10 Useful PHP String-Related Functions

No need to elaborate much on this one. Here are ten very useful functions for manipulating strings. Some are very simple and straightforward, but are still very useful.

I would normally use these in class called something like Common_Strings, and make each function static but I’ll just provide them here as functions for you to use as you please.

1. Replace Last Occurrence of a String

/**
* Replace the last occurrence of a string.
*
* @param string $search
* @param string $replace
* @param string $subject
* @return string
*/
function strReplaceLast ( $search, $replace, $subject ) {

	$lenOfSearch = strlen( $search );
	$posOfSearch = strrpos( $subject, $search );

	return substr_replace( $subject, $replace, $posOfSearch, $lenOfSearch );

}

2. Strip All Non-Alpha Numeric Characters and Spaces

/**
* Remove all characters except letters, numbers, and spaces.
*
* @param string $string
* @return string
*/
function stripNonAlphaNumericSpaces( $string ) {
	return preg_replace( "/[^a-z0-9 ]/i", "", $string );
}

3. Strip All Non-Alpha Numeric Characters

/**
* Remove all characters except letters and numbers.
*
* @param string $string
* @return string
*/
function stripNonAlphaNumeric( $string ) {
	return preg_replace( "/[^a-z0-9]/i", "", $string );
}

4. Remove All Non-Numeric Characters

/**
* Remove all characters except numbers.
*
* @param string $string
* @return string
*/
function stripNonNumeric( $string ) {
	return preg_replace( "/[^0-9]/", "", $string );
}

5. Remove All Non-Alpha Characters

/**
* Remove all characters except letters.
*
* @param string $string
* @return string
*/
function stripNonAlpha( $string ) {
	return preg_replace( "/[^a-z]/i", "", $string );
}

6. Remove All Excess White-Space

/**
* Transform two or more spaces into just one space.
*
* @param string $string
* @return string
*/
function stripExcessWhitespace( $string ) {
	return preg_replace( '/  +/', ' ', $string );
}

7. Format a String for a URL Slug

/**
* Format a string so it can be used for a URL slug
*
* @param string $string
* @return string
*/
function formatForUrl( $string ) {

	$string = stripNonAlphaNumericSpaces( trim( strtolower( $string ) ) );
	return str_replace( " ", "-", stripExcessWhitespace( $string ) );

}

8. Format an URL Slug into a Human Readable String

/**
* Format a slug into human readable string
*
* @param string $string
* @return string
*/
function formatFromUrl( $string ) {
	return str_replace( "-", " ", trim( strtolower( $string ) ) );
}

9. Get Unique Characters from a String

/**
* Get an array of unique characters used in a string. This should also work with multibyte characters.
*
* @param string $string
* @return mixed
*/
function getUniqueChars( $string, $returnAsArray=true ) {
    $unique = array_unique( preg_split( '/(?<!^)(?!$)/u', $string ) );
    if ( empty( $returnAsArray ) ) {
		$unique = implode( "", $unique );
    }
    return $unique;
}

10. Generate a Random String

Please note that the following method is not designed to be cryptographically secure. What this means is that it is feasible for an attacker to try and guess the output of this random string generator. If you do need something cryptographically secure, then you’re better off using PHP7’s random_int method or, alternatively, use the following library which can be used for v5.x versions of PHP: https://github.com/paragonie/random_compat. If you want to know more about why rand and mt_rand are not cryptographically secure, this is an excellent article: Predicting the output of PHP’s rand()

/**
* Generate a random string of specified length from a set of specified characters
*
* @param integer $size Default size is 30 characters.
* @param string $chars The characters to use for randomization.
*/
function randomString( $size=30, $chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" ) {

	$string = "";
	$length = strlen( $chars );

	for( $i=0; $i < $size; $i++ ) {
	    $string .= $chars{ rand( 0, $length ) };
	}

	return $string;

}

4 thoughts on “10 Useful PHP String-Related Functions

  1. Just wanted to say thanks for this, really useful set of functions.

    On a minor note, there is a typo in number 7, line 9 should read:

    $string = stripNonAlphaNumericSpaces( trim( strtolower( $string ) ) );

    you missed the a on the end of Alpha 😉

  2. The random sting is a PSEUDO-random string. This is not cryptographic secure. As this is often the main goal of using random strings, I would advice you to add a remark about that. It looks random but this will not stop hackers from guessing your generated code. The random string is based on the clock of the computer and hackers can guess this.
    There are cryptographic random functions in PHP.

    1. Hi wokste, thanks for replying and pointing this out. You are, of course, correct. It is not cryptographically secure; at the time this article was written, I was admittedly not knowledgeable about such things. If you do need something cryptographically secure, then you’re better off using PHP7’s random_int method or, alternatively, use the following library which can be used for v5.x versions of PHP: https://github.com/paragonie/random_compat. I will look at updating this article to reflect that.

Leave a Reply

Your email address will not be published. Required fields are marked *