Thursday, September 2, 2010

PHP String

  • A string variable is used to store and manipulate a piece of text. 
  • String variables are used for values that contains character strings.
  • After creating a string we can manipulate it. A string can be used directly in a function or it can be stored in a variable.
Below, the PHP script assigns the string "Hello World" to a string variable called $txt:

$txt="Hello World"; echo $txt;
output : HelloWorld

The Concatenation Operator
  • There is only one string operator in PHP.
  • The concatenation operator (.)is used to put two string values together.
  • To concatenate two variables together, use the dot (.) operator.
Example:
$txt1="Hello World";
$txt2="1234";
echo $txt1 . " " . $txt2;

output:
Hello World 1234

If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string.
Between the two string variables we added a string with a single character, an empty space, to separate the two variables.

Using the strlen() function

  • The strlen() function is used to find the length of a string.
Example:
echo strlen("Hello world!");

output:
12
The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string)


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 theposition of the first match. If no match is found, it will return FALSE.
Example:
echo strpos("Hello world!","world");


output:
6
As you see the position of the string "world" in our string is position 6. The reason that it is 6, and not 7, is that the first position in the string is 0, and not 1.


Commonly used String Functions

  • addslashes—Quote string with slashes.
  • explode —Split a string by string.
  • implode —Join array elements with a string.
  • join —Alias of implode().
  • md5 —Calculate the md5 hash of a string.
  • nl2br —Inserts HTML line breaks before all new lines in a string.
  • str_split —Convert a string to an array.
  • strcmp—Binary safe string comparison.
  • print —Output a string.
  • strtolower—Make a string lowercase.
  • strtoupper—Make a string uppercase.
  • trim —Strip whitespace(or other characters) from the beginning and end of a string.




No comments:

Post a Comment