PHP String


PHP strings are defined inside "" or '' pairs. Strings defined by "" will substitute the variables contained with their values, while '' will not.

<?PHP
$name="John Smith";
$str="His name is $name"; //His name is John Smith
$str2='His name is $name'; //His name is $name
?>

If string contains special characters such as ", \, $ etc, they should be escaped by a slash \ symbol. Character ' inside a '' defined string should also be escaped by \.
<?PHP
$name="John Smith";
echo "His name is \"$name\""; //His name is "John Smith"
echo 'His nmae is \'$name\''; //His name is '$name'
echo "His nmae is '$name'"; //His name is 'John Smith'
?>

PHP string can also be defined by <<< followed by a symbol, the symbol is self defined, here we use STR, and the string should be ended by the same symbol and a semicolon. Special characters inside the string do not need to be escaped. Variables inside the string will be substitute by their values, except associated array elements.
<?PHP
$str=<<<STR
His name is "John Smith";
STR;
echo "$str"; //His name is "John Smith"
?>

PHP string can be used as an array of characters.
<?PHP
$name="John Smith";
echo $name[0]; //J
echo $name[2]; //h
?>

strip_tags() delete the HTML and PHP symbols inside the string.
<?PHP
$str='<table><tr><td>name<td>address</table>';
$str2=strip_tags($str);  //nameaddress
?>

addslashes() and stripslashes() functions add and delete the slash "\" characters inside the string respectively. These functions are very important when PHP is working with databases.
<?PHP
$str="His name is \"John Smith\"";
echo $str; //His name is "John Smith"
echo addslashes($str); //His name is \"John Smith\"
?>

strlen() function returns length of the string.
<?PHP
$str="His name is \"John Smith\"";
echo strlen($str); //24
?>

strtolower(), strtoupper(), ucfirst(), ucwords() functions will change the string to lower case, upper case etc.
<?PHP
$str="His name is John Smith";
echo strtolower($str); //his name is john smith
echo strtoupper($str); //HIS NAME IS JOHN SMITH
echo ucfirst($str); //His name is John Smith
echo ucwords($str); //His Name Is John Smith
?>

trim() deletes space, new line, tab characters at the beginning and end of the string, chop() deletes spaces at the end of string, ltrim() function delete spaces at the beginning of the string.
<?PHP
$str="  this is php tutorial ";
echo "|" . trim($str) . "|";  //|this is php tutorial|
echo "|" . chop($str) . "|";  //| this is php tutorial|
echo "|" . ltrim($str) . "|";  //|this is php tutorial |
?>

htmlspecialchars() function converts some HTML special characters such as <, >, & and " into &lt;, &gt;, &amp; and &quot; etc.
<?PHP
$str='<table><tr><td>name<td>address</table>';
echo $str;  //<table><tr><td>name<td>address</table>
echo htmlspecialchars($str); 
//&lt;table&gt;&lt;tr&gt;&lt;td&gt;name&lt;td&gt;address&lt;/table&gt;
?>


More string functions include str_replace, substr_replace, strcmp(), strpos(), strrpos(), substr(), strrev(), strtr etc.