PHP Lesson 19: Search and replace strpos(), strlen(), str_replace(), str_ireplace()

Hello viewer, You can now have our Tutorial Lessons in your android mobile device and read it offline.
Download kotlin Programming APP on PlayStore
Download Website SEO Lessons APP on PlayStore

With PHP you can also search texts, and replace certain characters/words with another text.

If you want to check if some text is contained in another text, you can use the function strpos($text, $searchtext) at. This returns the position of the first occurrence if the searched text exists. If the text does not exist, false is returned.

<?Php
$text = "This is a small example for browsing, and we'll learn another way later.";
$position = strpos ($text, "on");
echo "Found at position: $position";
?>

In the above example for the text one sought. This string is found for the first time at the ninth position in the text (reminder: PHP starts counting from 0). The strpos() function distinguishes between upper and lower case. Here are a few more examples to illustrate how it works:

<?Php
$text = "This is a small example for browsing, and we'll learn another way later.";
echo "'one' found at position:" .strpos ($text, "on"). "<br />"; // Edition: 9
echo "'one' found at position:" .strpos ($text, "a"). "<br />"; // Edition: 15
echo "'On' found at position:" .strpos ($text, "On"). "<br />"; // Edition: 47
echo "'One' found at position:" .strpos ($text, "A"). "<br />"; // Edition: 47
?>

The string one is found for the first time in the word small, which is why we get 15 there. On and One is found for the first time at the beginning of the second movement.

As mentioned earlier, the function returns false if the text was not found. We can use this well in an if statement to check if a text contains a certain substring.

<?Php
$text = "This is a small example for browsing, and we'll learn another way later.";
$searchword = "I do not exist";
$position = strpos ($text, $searchword);

if ($position === false) {
   echo "string was not found";
} else {
   echo "Found at position: $position";
}
?>

Maybe one or the other noticed that we used three === instead of two == in the if-statement. For three equals signs, it is actually checked that the value of the variable is false. If there are two equals signs, a 0 would also be interpreted as false. This causes problems if the search word is directly at the beginning of the text as shown in the following example:

<? Php
$text = "This is a small example for browsing, and we'll learn another way later.";
$searchword = "this";
$position = strpos ($text, $searchword);

echo "With two equal signs, the search term '$suchword' became:";
if ($position == false) {// Attention, this was incorrectly using only 2 equal signs
   echo "not found";
} else {
   echo "found at position: $position";
}
echo "<br />";

echo "With three equal signs, the search term '$searchword' became:";
if ($position === false) {
   echo "not found";
} else {
   echo "found at position: $position";
}
?>

If you want to search independently of upper and lower case, we recommend the function stripos($text, $searchtext),

Output subtext

In the first section, we learned how to check if a search term exists in a text. Now we can use substr($text, $start, $length) Extract substrings from a text and have them output, for example. The third parameter, $length, is optional. If this is not specified, the rest of the string is output.

<?Php
$text = "This is a small example for browsing, and we'll learn another way later.";
echo substr ($text, 9, 11); // output: a little
?>

Using substr($text, 9, 11); we get 11 characters of the variable $ text from the 9th position. This is in this case, the position of the word one.

The function substr() is useful in many areas, for example, if we just want to print the beginning or the end of a text, we want to check it starts a text with certain characters or even to output text in the middle. Here are a few simple examples that you should go through and understand step by step.

<?Php
$text = "This is a small example for browsing, and we'll learn another way later.";
echo substr ($text, 0, 15). "<br />"; // prints the beginning of the text
echo substr ($text, 12). "<br />"; // prints everything from the 12th character
echo substr ($text, strlen ($text) -15). "<br />"; // Returns the last 15 characters
?>

In the last line, we determined the length of the text using the function strlen($text), We then deducted the number 15 and thus output the last 15 characters of the text. This is a bit easier by specifying a negative value for $start. Then it is counted from the end of the text. Also, the value $ length may be negative, then it will print to the end of the text:

<?Php
$text = "This is a small example for browsing, and we'll learn another way later.";
echo substr($text, strlen ($ text) -15). "<br />"; // Returns the last 15 characters
echo substr($text, -15). "<br />"; // Returns the last 15 characters

echo substr($text, -20, 10). <br /> "; // Returns 10 characters, begins 20 characters before the end of text

echo substr($text, 5, -10). "<br />"; // Returns all characters from position 5 to 10 characters before the end
echo substr($text, -25, -10). "<br />"; // Returns all characters from 25 characters before the end to 10 characters before the end
?>

As a small exercise, we now want to search for a string using strpos() and then output the 10 characters before and after. This works as follows:

<?php
$text = "This is a small example for browsing, and we'll learn another way later.";
$searchword = "example";
$position = strpos ($text, $searchword);

if ($position === false) {
   echo "search word was not found";
} else {
   $start_position = max (0, $position-10);
   $length = strlen ($searchword) + 10 + 10;
   echo substr ($text, $start_position, $length);
}
?>

This is a bit more complicated. If strpos returns false, we issue a message that the search term was not found. Otherwise, we first calculate the starting position for the output. We want to spend the 10 characters before the search term. To make sure that we do not get a negative start position, for example, if the search word value is below the first 10 characters, we still use the max () Function. So if $ position-10 should become negative, we set the starting value to 0.
The length of the output results from the length of the search word, plus 10 characters in each case before the search word and 10 characters after the search word. Finally, we use substr() to output the text before and after the search term.

Easy replacement

The simplest command for this is: str_replace (“Find”, “Replace”, $variable) ,

An example:

<?Php
$text = "This is a small example";
$text = str_replace ("is", "was", $text);
echo $text;
?>

With str_replace we replace is by was in the variable $ text and save this again in the variable $text.

It is important to know that str_replace distinguishes between uppercase and lowercase. If we want to replace a word, regardless of whether it is uppercase or lowercase, we can str_ireplace()  use:

<?Php
$text = "Replace Peter and peteR with another word";
$text = str_ireplace ("Peter", "Max", $text);
echo $text;
?>

Here both Peter and Peter are replaced by the word Max.

Note that str_replace () / str_ireplace () ignores word boundaries. So it does not matter in the text where the search string appears, whether at the beginning of the word, in the middle of the word or at the end of the word. Once there is a match, the text will be replaced accordingly. This can be an advantage, for example, if you want to replace ä throughout the text with an ae. But if for example, you want to replace the word he is using, it can have weird side effects:

<?Php
$text = "Who was at the door? Peter and he had robort with them.";
$text = str_replace ("he", "she", $text);
echo $text; // echo: Who was at the door? Peter and she had robort with them.
?>

One way around this problem is to check that it is really a standalone word, ie we also check that there are spaces before and after the word. Here we must not forget to add corresponding spaces in the new text:

<?Php
$text = "Who was at the door? Peter and he had robort with them.";
$text = str_replace (" he ", " she ", $text);
echo $text; // echo: Who was at the door? Peter and she had robort with them.
?>

Several substitutions at the same time

Of course, if you want to replace several expressions at once, you can apply several str_replace functions in succession. Or, instead of strings, you simply pass arrays that define the multiple substitutions. Here is an example:

<? Php
$text = "You should eat fruits, vegetables, and fiber daily.";
$healthy = array ("fruits", "vegetables", "fiber");
$yummy = array ("pizza", "beer", "ice cream");

$new_text = str_replace ($healthy, $yummy, $text);
echo $new_text; // You should eat pizza, beer and ice cream every day.
?>

In order to get a line break in HTML, it is well known not to press the Enter key, but we achieve this with the command <br />. Now it often happens that we want to convert line breaks of user input into corresponding HTML line breaks. This works either with the previously learned str_replace() function or with the nl2br($text)Short for new line to break ). Here is a small example. On the first page, the user enters text in a textarea, then we output the text accordingly:

<form action="site2.php" method="post">
Text: <br />
<textarea name="text" row="10" cols="50"></textarea>
<input type="submit" />
</form>

page2:

<?Php
$text = $ _POST['text'];
echo "Unformatted, the text looks like this: <br />";
echo $text;
 
echo "<br /> <br /> With str_replace this looks like this: <br />";
echo str_replace ("\n", "<br />", $text);
 
echo "<br /> <br /> With nl2br it looks like this: <br />";
echo nl2br($text);
?>

Try it with different inputs. The cleanest way to convert lines to HTML line breaks is to use the nl2br () function

About The Author

Related posts

Leave a Reply