In this PHP programming tutorial we will look at common string functions. String variables are used to store and manipulate text.
In the PHP script below we assign the text “Hello everybody” to a string variable $my_string and print the content of the variable:
<?php $my_string = “Hello everybody”; echo $my_string; ?>
Now that you know how to declare a string variable and how to print the content of the variable, let’s look at some common strings manipulation.
Sometimes you want to know the length of a string. With the PHP strlen() function you can do just that. Let’s look at an example:
<?php echo strlen("I’m sorry dave, I’m afraid I can’t do that."); ?>
The result of the statement will be a number (the length of the string including space and signs, not only the characters), in this case the number 43. As you can see this is very useful, because you can use this number for all kinds of thing. For instance you can use it in a loop to stop after the last character.
The PHP strpos() function is used to search for a character or string within a string. If the character is found the strpos() function will return the position of the first match. If strpos() can’t find the character in the string, it will return FALSE. Let’s look at an example:
<?php echo strpos(“Open the pod bay doors please, HAL”,”HAL”); echo strpos(“Open the pod bay doors please, HAL”,”H”); ?>
The position of the string “HAL” in the whole string is position 31 (the space before the string HAL.) The reason that it is 31 (space) and not 32 (the character H) is that the first position in the string is 0, and not 1.
Another thing, we use the string “HAL” as our search string. In the previous example both results returned the same number. But what if we do this (placing another H in the string):
<?php echo strpos(“Open the pod H bay doors please, HAL”,”HAL”); echo strpos(“Open the pod H bay doors please, HAL”,”H”); ?>
You’ll see that the second statement will return a different number than in the previous example. So make sure that you always place the complete string what you are looking for in the search part of strpos() function.
PHP has only one string operator. If you want to put two string values together you can use the concatenation operator (.) Let’s look at an example where we concatenate two strings:
<?php $str_one=”Hello“; $str_two=”World!”; echo $str_one . “ “. $str_two; ?>
The result will be “Hello World!”. As you can see we use the concatenation operator two times in the example. We do this because we want a space between the two strings.
These are just the most common string function you’ll probably use in the beginning.
HACKED BY SudoX — HACK A NICE DAY.