![]() |
|
Working with strings in PHP. Free online PHP and MySQL Web Database Programming Tutorial... |
| Lessons | Working with strings in PHP |
|
|
$myString = 'Single Quote String'; $myString2 = "Double Quote String"; In case the string is a large one and spans multiple lines you could use the PHP heredoc string as under: $myHeredocString = <<< ABC This is the text that will be included in the myHeredocString variable. Heredoc strings are very useful when dealing with large blocks of string variables. ABC; Note that the ABC after <<< is an identifier and it marks the beginning and end of the heredoc text block. You could use an identifier of your choice in place of ABC. To construct a heredoc string variable, we should provide an identifier after <<<, then the string, and then the same identifier to close the string. The closing identifier must begin in the first column of the line. String Manipulation Here we are going to look at some of the most common functions and operators used to manipulate strings in PHP. Printing Strings We use the echo statement to output or print a string. The argument to the echo statment can either be a string or a string variable. See the example below: <?php $txt="Hello World"; echo $txt; echo "Hello World Again"; ?> The output of the code above will be: Hello World Hello World Again String Concatenation To join or concatenate two strings we use the concatenation operator (.). The concatenation operator can be used either to join two strings or two string variables. See the example below: <?php $txt1="Hello World!"; $txt2=" We are back!"; echo $txt1 . " " . $txt2; ?> The output of the code above will be: Hello World! We are back! The strlen() function We use the strlen() function to find the length of a string. For example we can find the length of the string "Hello world!" as under: <?php echo strlen("Hello world!"); ?> The output of the code above will be: 12 Using the strpos() function The strpos() function is used to search for a string or character within a string. If a match is found in the string, this function will return the position of the first match. If no match is found, it will return FALSE. Let's try to find the string "world" in our string "hello world!": <?php echo strpos("Hello world!","world"); ?> The output of the code above will be: 6 If you are a keen observer, you might have noticed that the actual position of the string world in the string hello world! is 7 and not six. So what is heppening here? The answer is simple; PHP starts counting from 0 and not 1!
Next: PHP String Functions
|