Search
Close this search box.
Search
Close this search box.

Strings in Php

Concatenating Strings

Concatenation is an unwieldy term but a useful concept. It refers to the appending of one item onto another. Specifically, in programming, you concatenate strings. The period (.) is the operator for performing this action, and it’s used like so:

$var1 = 'Hello, ';
$var2 = 'world!';
$greeting = $var1 . $var2;
print $greeting; // output: Hello world!

Substrings

The Substr () PHP Function is used to return part of a string. It is written as substr (string, start, optional length);.

The string is whatever string you want to return a portion of.

The start is how many characters in to skip before starting. Setting this to 3 would skip the first three and start returning at the forth character. Setting this to a negative number will start counting backwards from the end of the string.

Length is an optional parameter. If you set this to a positive number, it will return that number of characters. If you set this to a negative number it will count that many numbers from the end of the string and return whatever is left in the middle.

Examples:
 <?php 
 // this will return bcdefghijk
 echo substr('abcdefghijk', 1);
 echo "<br>";

 // this will return defghijk
 echo substr('abcdefghijk', 3);
 echo "<br>";

 // this will return abc
 echo substr('abcdefghijk', 0, 3);
 echo "<br>";

 // this will return ijk
 echo substr('abcdefghijk', -3);
 echo "<br>";

 // this will return bcdefghij
 echo substr('abcdefghijk', 1, -1);
 echo "<br>";

 // this will return cdefgh
 echo substr('abcdefghijk', 2, -3);
 echo "<br>";
 ?> 

Using Regular Expressions

Sometimes you need to compare character strings to see whether they fit certain characteristics, rather than to see whether they match exact values. For example, you may want to identify strings that begin with S or strings that have numbers in them. For this type of comparison, you compare the string to a pattern. These patterns are called regular expressions.

For a more detailed tutorial, visit http://www.tuxradar.com/practicalphp/4/8/1.

Case folding

$text = 'my text';
echo mb_convert_case($text, MB_CASE_TITLE); // echoes 'My Text'
echo mb_convert_case($text, MB_CASE_UPPER); // echoes 'MY TEXT'
$text = 'MY TEXT';
echo mb_convert_case($text, MB_CASE_LOWER); // echoes 'my text'