Web Design and Programming Pt 9 PHP Strings

StringsHere I show you how to use many string manipulation methods in PHP. Also, I finish showing you how to use regular expressions.

You should watch the previous 2 PHP Regular Expressions video tutorials before you continue on to this one. They are avaialable here PHP Regular Expressions & PHP Regular Expressions Pt 2

I specifically cover the following PHP Methods in this tutorial:

  • preg_match_all
  • preg_replace
  • substr
  • strpos
  • preg_split
  • strlen
  • strcmp
  • strip_tags
  • And more…

Like always the code used follows the video. Use it in any way you like. If you have any questions or comments leave them below.

Code From the Video

<title><?php echo “Regular Expressions”;?></title>


$randomStr = “Mailman Mailwoman Jennifer Jenny Jen Doctor Doug Dog”;

# Find different versions of the name Jennifer
preg_match_all(‘%Je[nifery]{1,6}%’, $randomStr, $matchName);

foreach($matchName as $result)
foreach($result as $found)
echo $found . “<br /><br />”;

# Replace the Regex with something else using preg_replace
$randStr = “Dick and Jane fetched a bucket of water”;
echo preg_replace(“%Dick%”, “Paul”, $randStr). “<br /><br />”;

# Replacing Strings
echo str_replace(“Jane”, “Erica”, $randStr). “<br />”;

# Returning part of a string
echo substr($randStr,9,4) . “<br />”;

# Return the position of the substring
echo strpos($randStr, “fetched”). “<br />”;

# ———-
# Split a string based off a Regex with preg_split
$chairPpl = “John Thompson (CEO) Mark Summers (CFO) Betty Wu (CTO) “;
$noTitle = preg_split(“%\s\(.{3}\)\s%”, $chairPpl);
foreach($noTitle as $found)
echo $found . “<br />”;

# Find the length of a string
echo strlen($chairPpl) . “<br />”;
# ———-

# Compare strings
$strOne = “Doctor Jay”;
$strTwo = “Doctor Jay”;
$strThree = “he went there”;

# Returns neg number if strOne < strTwo, 0 if equal, else a positive number
echo strcmp($strOne,$strTwo). “<br />”;
echo strcasecmp($strOne,$strTwo). “<br />”;

# Changing String Case
echo ucfirst($strThree) . “<br />”;
echo ucwords($strThree) . “<br />”;
echo strtolower($strOne) . “<br />”;
echo strtoupper($strOne) . “<br />”;
# ———-

# trim removes white space from beginning and end of a string
# ltrim removes white space from left side
# rtrim removes white space from right

# ———-

# Strip HTML Tags
$htmlText = “<head><title>My Web Page</title></head>”;
echo strip_tags($htmlText) . “<br />”;

Leave a Reply

Your email address will not be published.