Changes

Jump to: navigation, search

Working with Strings and Text in PHP

1,326 bytes added, 17:08, 4 June 2007
Extracting and Replacing Substrings in PHP
== Extracting and Replacing Substrings in PHP ==
 
A sub-section of any PHP string can be extracted and replaced using the ''substr'' and ''substr_replace'' functions.
 
The ''substr'' function takes two arguments which represent the source string and the start index. An optional third argument specifies the length of the substring (if no length is specified the end of the string is assumed). The function retruns the requested substring:
 
<pre>
 
<?php
 
$myString = "There is a cat in the tree.";
 
$subString = substr ($myString, 11, 3);
 
echo "subString = $subString <br>";
 
?>
</pre>
 
The above example will extract the word ''cat'' from the string.
 
The substr_replace function takes up to four arguments. The firsdt is the source string on which the replace is to be performed. The second argument is the replacement string. The third argument specifies the index offset of the starty of the replacement. The optional fourth argument defines number of characters from tyhe offset point to include in the replacement (useful if your replacement text is shorter than the original text being replaced).
 
 
We can nopw extend our example to replace some text in our string:
 
<pre>
<?php
$myString = "There is a cat in the tree.";
 
$subString = substr ($myString, 11, 3);
 
echo "subString = $subString <br>";
 
$myString = substr_replace ($myString, "dog", 11, 3");
?>
</pre>

Navigation menu