Changes

Jump to: navigation, search

Working with Strings and Text in PHP

1,574 bytes added, 17:30, 4 June 2007
Extracting and Replacing Substrings in PHP
It is perfectly valid to replace one substring with another of different length. It is also possible to simply remove a substring by simply passing in an empty replacement string to the substr_replace fucntion.
 
== Replacing All Instances of a Word in a PHP String ==
 
All the instances of a word in a string can be replaced using the PHP ''str_replace'' function. ''str_replace'' takes 3 required and one optional argument. The first argument represents the string to be replaced, the second the replacement value and the third the target string. The optional fourth argument is a reference to a variable where the results of the repalcement will be stored for subsequent inspection.
 
A simple example is as follows:
<pre>
<?php
$myString = "There is a cat in the tree, and I think it is my cat!";
 
echo "Original String = $myString<br>";
 
$myString = str_replace ("cat", "dog", $myString);
 
echo "New String = $myString<br>";
?>
</pre>
 
Resulting in the following output:
 
<tt>Original String = There is a cat in the tree, and I think it is my cat!</tt><br>
<tt>New String = There is a dog in the tree, and I think it is my dog!</tt>
 
If the search and replacement values are arrays of words then each word in the search array is replaced by the corresponding value in the replacement array. For example:
 
<pre>
<?php
$myString = "There is a cat in the tree, and I think it is my cat!";
 
echo "Original String = $myString<br>";
 
$myString = str_replace (array("is", "cat", "tree"), array("was", "dog", "car"), $myString);
 
echo "New String = $myString<br>";
?>
</pre>
 
The above example results in the following output:
 
<tt>Original String = There is a cat in the tree, and I think it is my cat!</tt><br>
<tt>New String = There was a dog in the car, and I think it was my dog!</tt>

Navigation menu