PHP has a lot of string functions, the ones used in this post are mostly of the str_ variety except there are many ways and options to do the tasks done in these examples. This post consists of handling strings if you need to:
$mystring = "This is my string. It is 11:08pm"; $remove_word = str_replace("string", "rope", $mystring);//This is my rope. It is 11:08pm $mystring = "A string that contains naughty words like flog and muppet"; $filter = array("flog", "muppet", "swearword1", "swearword2", "etc"); $filter_string = str_replace($filter, "****", $mystring);//A string that contains naughty words like **** and **** $mystring = "This is a good string, It is good because i made it."; $count = str_replace("good", "", $mystring, $count);//2
$mystring = "My good string, isnt it so good?!"; $array = str_word_count($mystring, 1); print_r($array);//Array ( [0] => My [1] => good [2] => string [3] => isnt [4] => it [5] => so [6] => good ) echo $array[2];//string
echo strlen("This is the example string"); //26
$mystring = 'Yes it is another example string!'; $find = 'string'; $position = strpos($mystring, $find); if ($position === false) { echo "The word '$find' was not found in the string '$mystring'"; } else { echo "The word '$find' was found in the string '$mystring'
and exists at position $position"; }
$mystring = "This string was made at 11:08:22"; $example = substr($mystring, -8);//11:08:22 $example2 = substr($mystring, -8, 5);//11:08 $mystring2 = "Time: 11:08:22 success"; $example4 = substr($mystring2, -6, -8);//11:08:22 $example4 = substr($mystring2, -6, -11);//11:08
$mystring = "Twitter username @gary_fox"; $username = substr($mystring, strpos($mystring, "@") + 1); echo $username;//gary_fox //or $username = explode('@', $mystring, 2)[1];//gary_fox //kinda echo strrchr("Twitter username @gary_fox","@");//@gary_fox
These i in my belief handy and a good range of string handlers for a beginner in PHP. You can do quite a bit with the prebuilt str_ functions, I look forward to making another post going over more string handling and manipulation.
A drained and empty Kennington reservoir images from a drone in early July 2024. The…
Merrimu Reservoir from drone. Click images to view larger.
Using FTP and PHP to get an array of file details such as size and…
Creating and using Laravel form requests to create cleaner code, separation and reusability for your…
Improving the default Laravel login and register views in such a simple manner but making…
Laravel validation for checking if a field value exists in the database. The validation rule…