PHP-SUBSTRING,STRING REPLACE,MULTIPLEREPLACE,CAPITALISE


finding  all  occurrences  in  a  string  with  offset


One of the limitations of strpos is that it only returns the position of the very first match. If there are 5,000 other matches in the string you would be none the wiser, unless you take action!
There is a third (optional) argument to strpos that will let you specify where to begin your search of the string. If you were to store the position of the last match and use that + 1 as an offset, you would skip over the first match and be find the next one.

PHP Code:

$numberedString = "1234567890123456789012345678901234567890";

$fivePos = strpos($numberedString, "5");
echo "The position of 5 in our string was $fivePos";
$fivePos2 = strpos($numberedString, "5", $fivePos + 1);
echo "<br />The position of the second 5 was $fivePos2";

php str_replace function
Another key tool to have in your programming toolbox is the ability to quickly replace parts of a PHP string with new values. The str_replace function is similar to a word processor's "Replace All" command that lets you specify a word and what to replace it with, then replaces every occurrence of that word in the document.

str_replace parameters

str_replace has three parameters that are required for the function to work properly. str_replace(search, replace, originalString).
1.     search - This is what you want to search your string for. This can be a string or an array.
2.     replace - All matches for search will be replaced with this value. This can be a string or an array.
3.     originalString - This is what search and replace will be operating on. Thestr_replace function will return a modified version of originalString when it completes.

 

str_replace simple example

Imagine we are working at a school district and need to create a webpage for the students' parents. The webpage has an introduction string that we need to customize depending on if the student is male or female. With str_replace this is mighty easy.

PHP Code:

//string that needs to be customized

$rawstring = "Welcome Birmingham parents. Your replaceme is a pleasure to have!";


//male string

$malestr = str_replace("replaceme", "son", $rawstring);


//female string

$femalestr = str_replace("replaceme", "daughter", $rawstring);


echo "Son: ". $malestr . "<br />";

echo "Daughter: ". $femalestr;

 

str_replace arrays: multiple replaces in one

In the last example we only needed to replace one word replaceme in our string, but what if we wanted to replace many words? We could just use the function multiple times to get the job done, or we could create an array ofplaceholders and a second array of replace values to get it all done in one function call.
The key thing to understand with this technique is that you are creating two arrays that will be used to swap values. The first item in placeholders will be replaced by the first item in the replace values, the second item of placeholdersreplaced with the second in replace values and so on and so forth.
Let's extend our simple example to be a complete form letter addressed to a student's parents.

PHP Code:

//string that needs to be customized
$rawstring = "Welcome Birmingham parent! <br />
                    Your offspring is a pleasure to have! 
                    We believe pronoun is learning a lot.<br />
                    The faculty simple adores pronoun2 and you can often hear 
                    them say \"Attah sex!\"<br />";

//placeholders array
$placeholders = array('offspring', 'pronoun', 'pronoun2', 'sex');
//male replace values array
$malevals = array('son', 'he', 'him', 'boy');
//female replace values array
$femalevals = array('daughter', 'she', 'her', 'girl');

//male string
$malestr = str_replace($placeholders, $malevals, $rawstring);

//female string
$femalestr = str_replace($placeholders, $femalevals, $rawstring);

echo "Son: ". $malestr . "<br />";
echo "Daughter: ". $femalestr
 
;


php substr_replace function
The function substr_replace introduces some additional functionality to compliment str_replacesubstr_replace is a more mathematically based replace function, which relies on starting points and lengths to replace parts of strings, as opposed to searching and replacing.

substr_replace's four parameters

There are three required parameters for the substr_replace function (original string, replacement string, starting point) and one that's optional (length).
1.     original string - This is your original string that will be operated on.
2.     replacement string - This string will be used to replace everything in the string from the starting point to the ending point (specified by length).
3.     starting point - This is the place in the original string that will be used to mark the replacement's beginning. A negative value specifies the number of characters from the end of the string.
4.     optional length - How many characters from the original string will be replaced. If no length is specified then the end of the string is used. If a value of 0 is used then no characters will be replaced and an insert is performed. A negative value specifies the number of characters from the end of the string.

substr_replace on your mark

This example of substr_replace shows what happens when you omit thelength parameter at various starting points.

PHP Code:

//string that needs to be customized
$original = "ABC123 Hello Mr. Cow! DEF321";

//starting point 5
$sp5 = substr_replace($original, "Five", 5);
//starting point 12
$sp12 = substr_replace($original, "Twelve", 12);
//starting point 0
$sp0 = substr_replace($original, "Zero", 0);
//starting point -1
$spneg1 = substr_replace($original, "Negative 1", -1);

//Echo each string
echo "Original String: $original <br />";
echo "Starting Point 5: $sp5 <br />";
echo "Starting Point 12: $sp12 <br />";
echo "Starting Point 0: $sp0 <br />";
echo "Starting Point -1: $spneg1 ";

As you can see, when you don't specify the fourth parameter, length, everything after the starting point is replaced by the second parameterreplacement string.
Note: The first replacement occurred at position 5, which in $original was the character 3. This 3 and everything onward was replaced with the replacement string. Remember that you start counting character to begin from zero. The $original string could be labeled as so:
  • Letter A - Position 0
  • Letter B - Position 1
  • Letter C - Position 2
  • Letter 1 - Position 3
  • Letter 2 - Position 4
  • Letter 3 - Position 5

substr_replace specifying a length

If you want to get any sort of precision out of this function you're going to have to get into the nitty gritty of specifying the exact length of characters you want replaced in your original string.
Imagine that you want to get rid of those ugly pseudo references (ABC123, DEF321) at the beginning and end of the string. Since both of those strings are a length of 6 and we know one is at the very beginning of the string and the other is at the very end of the string we should probably use a starting point of 0 for ABC123 and a value of -6 for DEF321. By having a replacement string of nothing "" we can do something similar to select and delete that we often do in a word processor.

PHP Code:

//string that needs to be customized

$original = "ABC123 Hello Mr. Cow! DEF321";


//remove ABC123 and store in $cleanedstr

$cleanedstr = substr_replace($original, "", 0, 6);

//remove DEF321 from $cleanedstr

$cleanedstr2 = substr_replace($cleanedstr, "", -6, 6);


//Echo each string

echo "Original String: $original <br />";

echo "Clean #1: $cleanedstr <br />";

echo "Clean #2: $cleanedstr2";

 

substr_replace perform an insert

By setting the length parameter to zero you can stop substr_replace from removing anything from the original string and just add to it. If we wanted to add a second and third person to our $original string we would want to do this insert operation. Note: instead of counting the characters we've used a couple other PHP functions to figure out the starting positions for us.

PHP Code:

//string that needs to be customized
$original = "Hello Mr. Cow!";

// Get the position of Mr. Cow
$cowpos = strpos($original, "Mr. Cow");

// Find where Mr. Cow ends by adding the length of Mr. Cow
$cowpos_end = $cowpos + strlen("Mr. Cow");

// Insert Mrs. Bear after Mr. Cow
$mrsbear = substr_replace($original, " and Mrs. Bear", $cowpos_end, 0);

// Insert Sensei Shark before Mr. Cow
$senseishark = substr_replace($mrsbear, "Sensei Shark, ", $cowpos, 0);


//Echo each string
echo "Original String: $original <br />";
echo "After Mrs. Bear: $mrsbear <br />";
echo "After Sensei Shark: $senseishark";
 
php - string capitalization functions
If you've ever wanted to manipulate the capitalization of your PHP strings, then this lesson will be quite helpful to you. PHP has three primary capitalization related functions: strtoupper, strtolower and ucwords. The function names are pretty self-explanatory, but why they are useful in programming might be new to you.
rs will remain the same.

PHP Code:

$originalString = "String Capitalization 1234";


$upperCase = strtoupper($originalString);

echo "Old string - $originalString <br />";

echo "New String - $upperCase";

 

capitalizing the first letter - ucwords
Titles of various media types often capitalize the first letter of each word and PHP has a time-saving function that will do just this.

PHP Code:

$titleString = "a title that could use some hELP"; 
 
$ucTitleString = ucwords($titleString);
echo "Old title - $titleString 
";
echo "New title - $ucTitleString";
Notice that the last word "hELP" did not have the capitalization changed on the letters that weren't first, they remained capitalized. If you want to ensure thatonly the first letter is capitalized in each word of your title, first use the strtolowerfunction and then the ucwords function.

PHP Code:

$titleString = "a title that could use some hELP";

$lowercaseTitle = strtolower($titleString);
$ucTitleString = ucwords($lowercaseTitle);
echo "Old title - $titleString <br />";
echo "New title - $ucTitleString";

Comments