PHP String Tutorials

PHP only supports a 256-character set, and hence does not offer native Unicode support.

Replace a word inside a string

$str = "Kotlin can be used to develop mobile app.";
$result = str_replace("mobile", "Android", $str);

Remove non-alphanumeric characters

preg_match() perform regular expression search and replace. We use it to remove non-alphanumeric characters.

$str = 'TL Templates @2020';
$str = preg_replace( '/[\W]/', '', $str);
echo $str; //output: TLTemplates2020
$str = preg_replace( '/[^a-z0-9 ]/i', '', $str);
echo $str; //output: TL Templates 2020

Remove all special characters from a string

$string = 'a|" duck!#%%*)[email protected]£^ &$8says hello';
echo preg_replace('/[^A-Za-z0-9 ]/', '', $string);
//output: a duck55 8says hello

Split a comma delimited string into an array

Both preg_split and explode can be used.

$str = "ID,Name,Age,Email,Username";  
$arr = preg_split("/\,/", $str); 
$arr = explode(',', $str);

Check if a string contains a specific word

$a = 'The most famous CMS written in PHP is Laravel.';
if (strpos($a, 'PHP') !== false) {
    echo 'It is true';
}

Generate a random, unique, alphanumeric string

//list all characters you want to generate
$base = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; 
//shuffle characters in the string
$base = str_shuffle($base);
//take a number of characters out
$length = 10;
$randomized_string = substr($base,  0, $length);

Loop through all characters of a string

$chars_array = str_split($string);
foreach ($chars_array as $key => $char) {
	echo $char;
}

Get the first character in a string

Strings in PHP can be treated like character arrays so we can get each character by calling out its index.

Another approach is to use mb_substr() and substr(). mb_substr supports Unicode character.

$text = 'This is my text';
echo $text[0]; //output: 'T'

//use substr
echo substr($string, 0, 1); //output: 'T'
//use mb_substr
$text = 'ê123ë';
echo mb_substr($text, 0, 1, "UTF-8"); //output: 'ê'

Leave a Comment

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

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close