PHP String Functions
PHP String functions are helpful in maipulating strings, keep in mind strings are text matter in any website/program. If we want to convert a paragraph to lowecase, capitalize only first character or any other manipulation, string functions will be helpfull.
Convert text to lower case
echo strtolower('WELCOME TO AMSOL E-TUTOR');
Convert text to upper case
echo strtoupper('welcome to amsol e-tutor');
Convert first letter of text to upper case
echo ucfirst('abdul rehman');
Convert first letter of each word in a text to upper case
echo ucwords('abdul rehman baig ');
Comparing two strings, keep in mind PHP is case sensitive. It returns true if strings macthes 100%.
echo strcmp("AMSOL Kutur ","amsol Tutor");
Check similar text
$TEXT1 ="Bill Gates"; $TEXT2 = "Bill Betes"; $TEXT3 = similar_text($TEXT1, $TEXT2, $PERCENT); echo ($TEXT3); echo ($PERCENT;
Repeat any character n times,
echo $RPT = str_repeat("*", 95);
Find and replace text
$TEXT = "Learn PHP String functions"; $TXT_SEARCH = "String"; $TXT_REPLACE = "Number"; print $TEXT . "
"; $TEXT_NEW = str_replace($TXT_SEARCH, $TXT_REPLACE, $TEXT); echo $TEXT_NEW;
Count words in a text
$num_of_words = str_word_count("The word count function"); print $num_of_words;
Count characters in a text
echo $CHARS = strlen("This is text text");
check a string for any pattern
$email = "test@amsol.biz"; $email_end = substr($email, strlen($email) - 4); if ($email_end == ".biz" ) { print "ends in .biz"; } else { print "doesn't end in .biz"; }
The trim() function removes whitespace from both sides of a string. We use mostly to purify the input entered by a user, where space character may be entered in start or end of a string.
$TXT = ' hello '; eco trim($TXT);
The trim() function can also remove other predefined characters from both sides of a string.
$TXT = ' hello and welcome ' echo trim($str,"Hdw!");
Wrap a string into new lines when it reaches a specific length:
$str = "An example of a long word is: Supercalifragulistic"; echo wordwrap($str,15,"
\n");
Convert the predefined characters "<" (less than) and ">" (greater than) to HTML entities:
$str = "This is some bold text."; echo htmlspecialchars($str);
The HTML output of the code above will be => This is some <b>bold</b> text.
and browser output of the code above will be => This is some bold text
Convert characters to HTML entities:
$TXT = 'Visit amsol.biz'; echo htmlentities($TXT);
The HTML output of the code above will be =>
<a href="https://www.w3schools.com">Go to w3schools.com</a>
The browser output of the code above will be =>
Visit amsol.biz
Split the string after each character and add a "." after each split.
$str = "Hello world!"; echo chunk_split($str,1,".");