PHP - String

> Procedural Languages > Php

1 - About

The string in PHP is implemented as an array of bytes and an integer indicating the length of the buffer. It has no information about how those bytes translate to characters, leaving that task to the programmer.

3 - Initialization

3.1 - Quotes

3.1.1 - Single Quoted

  • enclose it in single quotes (the character ').
echo 'this is a simple string';
Advertising

3.1.2 - Double-quoted

If the string is enclosed in double-quotes (“), PHP will interpret more escape sequences for special characters such as:

  • Carriage return,
  • Line feed
echo 'this is a simple string with a end of line\r\n';

3.2 - Doc

3.2.1 - Heredoc

$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

3.2.2 - Nowdoc

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc.

$str = <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;

4 - Function

4.1 - Indexing

// Get the first character of a string
$str = 'This is a test.';
$first = $str[0];
 
// Get the third character of a string
$third = $str[2];
 
// Modify the third character of a string
$str[3] = 'e';

4.2 - Length

strlen($str)

4.3 - String function

4.4 - Replace

$lastPart = str_replace("/", "", $lastPart);
Advertising

4.5 - Split

  • Count the number of line an HTML document by splitting by the p, h, br,tr,li element
$localCount = count(preg_split("/<\/p>|<\/h[1-9]{1}>|<br|<\/tr>|<\/li>/",$section['content']));

4.6 - Contains

$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);
 
// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
} else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}

5 - Documentation / Reference