Strings And Patterns - nogsantos/study-zce-php-certification-codes GitHub Wiki

String Basics

  • Heredoc Syntax: A heredoc string is delimited by the special operator <<< followed by an identifier. Close the string using the same identifier, optionally followed by a semicolon, placed at the very beginning of its own line
<?php
$who = "World";
echo <<<TEXT
   So I said, "Hello $who"
TEXT;
?>
  • Using Strings as Arrays: You can access the individual characters of a string as if they were members of an array. String character indices are zero-based For example:
<?php
$string = 'abcdef';
echo $string[1]; // Outputs 'b'

//This approach can be very handy when you need to scan a string one character at a time:
$s = 'abcdef';
for ($i = 0; $i < strlen ($s); $i++) {
   if ($s[$i] > 'c') {
      echo $s[$i];
   }
}
?>

Escaping Literal Values

  • echo 'This is \'my\' string';
  • $a = 10; echo "The value of \$a is \"$a\".";
  • echo "Here's an escaped backslash: - \ -";
  • echo "Here's a literal brace + dollar sign: {\$";

Heredoc strings provide the same escaping mechanisms as double-quote strings, with the exception that you do not need to escape double quote characters, since they have no semantic value.

Functions

int strlen( string $string )
Retorna o tamanho da dada string.

<?php
$str = 'abcdef';
echo strlen($str); // 6
?>

string strtr ( string $str , string $from , string $to )
Esta função retorna uma cópia de str, traduzindo todas as ocorrências de cada caractere em from para o caractere correspondente em to.
Se from e to são de comprimentos diferentes, os caracteres extras no mais longo dos dois são ignorados.

<?php
// Single character version
echo strtr ('abc', 'a', '1'); // Outputs 1bc

// Multiple-character version
$subst = array (
   '1' => 'one',
   '2' => 'two',
);
echo strtr ('123', $subst); // Outputs onetwo3
?>

int strcmp ( string $str1 , string $str2 ) (diferencia maiúsculas e minúsculas.)
int strcasecmp ( string $str1 , string $str2 ) () (Não diferencia maísculas de minúsculas)
Comparação de strings para binário

<?php
$str = "Hello World";
if (strcmp($str, "hello world") === 0) {
   // We won’t get here, because of case sensitivity
}
if (strcasecmp($str, "hello world") === 0) {
   // We will get here, because strcasecmp()
   // is case-insensitive
}
?>

A further variant of strcasecmp(), strncasecmp() allows you to only test a given number of characters inside two strings. For example:

<?php
$s1 = 'abcd1234';
$s2 = 'abcd5678';
// Compare the first four characters
echo strncasecmp ($s1, $s2, 4);
?>

int strpos ( string $haystack , string $needle [, int $offset ] )
Retorna a posição numérica da primeira ocorrência de needle dentro de haystack.

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note o uso de "==="(identidade), simples "==" (igualdade)  não funcionaria como esperado
// por causa da posição de 'a' é 0 (primeiro) caractere.
if ($pos === false) {
    echo "A string '$findme' não foi encontrada na string '$mystring'";
} else {
    echo "A string '$findme' foi encontrada na string '$mystring'";
    echo " e existe na posição $pos";
}
?>

string strstr ( string $haystack , mixed $needle [, bool $before_needle ] ) Retorna parte da string haystack a partir da primeira ocorrência de needle até o final de haystack.

<?php
$email  = '[email protected]';
$domain = strstr($email, '@');
echo $domain; // prints @example.com

$user = strstr($email, '@', true); // A partir do PHP 5.3.0
echo $user; // prints name
?>

Both strpos() and strstr() are case sensitive and start looking for the needle from the beginning of the haystack. However, PHP provides variants that work in a case-insensitive way or start looking for the needle from the end of the haystack stripos() and stristr().
// Reverse search
echo strrpos (’123123’, ’123’); // outputs 3

int strspn ( string $str1 , string $str2 [, int $start [, int $length ]] )
Encontra o comprimento do segmento inicial combinando com a máscara.

<?php
$string = '133445abcdef';
$mask = '12345';
echo strspn ($string, $mask); // Outputs 6
?>

int strcspn ( string $str1 , string $str2 [, int $start [, int $length ]] )
Retorna o tamanho do segmento inicial de str1 que não contém nenhum dos caracteres em str2.
The strcspn() function works just like strspn(), but uses a blacklist approach in-stead—that is, the mask is used to specify which characters are disallowed, and the function returns the length of the initial segment of the string that does not contain any of the characters from the mask.

Both strspn() and strcspn() accept two optional parameters that define the starting position and the length of the string to examine. For example:

<?php
$string = '1abc234';
$mask = 'abc';
echo strspn ($string, $mask, 1, 4);
?>

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) [case-sensitive]
mixed str_ireplace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) [case-insensitive]
Esta função retorna uma string ou um array com todas as ocorrências de search em subject substituídas com o valor dado para replace.

<?php
// Fornece: você comeria pizza, cerveja e sorvete todos os dias
$frase  = "você comeria frutas, vegetais, e fibra todos os dias.";
$saudavel = array("frutas", "vegetais", "fibra");
$saboroso   = array("pizza", "cerveja", "sorvete");
$novafrase = str_replace($saudavel, $saboroso, $frase);
?>

mixed substr_replace ( mixed $string , string $replacement , int $start [, int $length ] ) substr_replace() substitui uma cópia de string delimitada pelos parâmetros start e (opcionalmente) length com a string dada em replacement.
Combining substr_replace() with strpos() can prove to be a powerful tool.
For example:

<?php
$user = "[email protected]";
$name = substr_replace($user, "", strpos($user, ’@’);
echo "Hello " . $name;
?>

By using strpos() to locate the first occurrence of the @ symbol, we can replace the rest of the e-mail address with an empty string, leaving us with just the username, which we output in greeting.

string substr ( string $string , int $start [, int $length ] )*
Retorna a parte de string especificada pelo parâmetro start e length.

<?php
$x = '1234567';
echo substr ($x, 0, 3); // outputs 123
echo substr ($x, 1, 1); // outputs 2
echo substr ($x,-2); // outputs 67
echo substr ($x,1); // outputs 234567
echo substr ($x,-2, 1); // outputs 6
?>

string sprintf ( string $format [, mixed $args [, mixed $... ]] ) [o mesmo é utilizado para printf()]
Retorna uma string produzida de acordo com a string de formatação format.
Um especificador de tipo que diz que o argumento deve ser tratado como do tipo. Os tipos possivéis são:

  • % - Um caractere porcento. Não é requerido neenhum argumento.
  • b - O argumento é tratado com um inteiro, e mostrado como um binário.
  • c - O argumento é tratado como um inteiro, e mostrado como o caractere ASCII correspondente.
  • d - O argumento é tratado como um inteiro, e mostrado como um número decimal com sinal.
  • e - o argumento é tratado como notação científica (e.g. 1.2e+2). O especificador de precisão indica o número de dígitos depois do ponto decimal desde o PHP 5.2.1. Em versões anteriores, ele pegava o número de dígitos significantes (ou menos).
  • u - O argumento é tratado com um inteiro, e mostrado como um número decimal sem sinal.
  • f - O argumento é tratado como um float, e mostrado como um número de ponto flutuante (do locale).
  • F - o argumento é tratado como um float, e mostrado como um número de ponto flutuante (não usado o locale). Disponível desde o PHP 4.3.10 e PHP 5.0.3.
  • o - O argumento é tratado com um inteiro, e mostrado como un número octal.
  • s - O argumento é tratado e mostrado como uma string.
  • x - O argumento é tratado como um inteiro, e mostrado como um número hexadecimal (com as letras minúsculas).
  • X - O argumento é tratado como um inteiro, e mostrado como um número hexadecimal (com as letras maiúsculas).
<?php
$n = 123;
$f = 123.45;
$s = "A string";
printf ("%d", $n); // prints 123
printf ("%d", $f); // prints 123
// Prints "The string is A string"
printf ("The string is %s", $s);
// Example with precision
printf ("%3.3f", $f); // prints 123.450
// Complex formatting
function showError($msg, $line, $file){
    return sprintf("An error occured in %s on "."line %d: %s", $file, $line, $msg);
}
showError ("Invalid deconfibulator", __LINE__, __FILE__);
?>

Perl-compatible Regular Expressions PCRE

Metacharacters
The term "metacharacter" is a bit of a misnomer—as a metacharacter can actually be composed of more than one character. However, every metacharacter represents a single character in the matched expression. Here are the most common ones:

  • . Match any character
  • ˆ Match the start of the string
  • $ Match the end of the string
  • \s Match any whitespace character
  • \d Match any digit
  • \w Match any "word" character

Metacharacters can also be expressed using grouping expressions. For example, a series of valid alternatives for a character can be provided by using square brackets: /ab[cd]e/
The expression above will match both abce and abde. You can also use other metacharacters, and provide ranges of valid characters inside a grouping expression: /ab[c-e\d]/ This will match abc, abd, abe and any combination of ab followed by a digit.

The preg_match() function can be used to match a regular expression against a given string. The function returns integer 1 if the match is successful, and can return all the captured subpatterns in an array if an optional third parameter is passed by reference. Here's an example:

<?php
$name = "Davey Shafik";
// Simple match
$regex = "/[a-zA-Z\s]/";
if (preg_match($regex, $name)) {
  // Valid Name
}
// Match with subpatterns and capture
$regex = '/^(\w+)\s(\w+)/';
$matches = array();
if (preg_match ($regex, $name, $matches)) {
   var_dump ($matches);
}
?>

return with the following values:

<?php
array(3) {
    [0]=> string(12) "Davey Shafik"
    [1]=> string(5) "Davey"
    [2]=> string(6) "Shafik"
}
?>

The preg_match_all() function allows you to perform multiple matches on a given string based on a single regular expression. For example:

<?php
$string = "a1bb b2cc c2dd";
$regex = "#([abc])\d#";
$matches = array();
if (preg_match_all ($regex, $string, $matches)) {
   var_dump ($matches);
}
?>

Using PCRE to Replace Strings

Whilst str_replace() is quite flexible, it still only works on "whole" strings, that is, where you know the exact text to search for. Using preg_replace(), however, you can replace text that matches a pattern we specify. It is even possible to reuse captured subpatterns directly in the substitution string by prefixing their index with a dollar sign. In the example below, we use this technique to replace the entire matched pattern with a string that is composed using the first captured subpattern ($1).

<?php
$body = "[b]Make Me Bold![/b]";
$regex = "@\[b\](.*?)\[/b\]@i";
$replacement = '<b>$1</b>';
$body = preg_replace($regex, $replacement, $body);
?>

Just like with str_replace(), we can pass arrays of search and replacement arguments and we can also pass in an array of subjects on which to perform the search-and-replace operation. This can speed things up considerably, since the regular expression (or expressions) are compiled once and reused multiple times. Here’s an example:

<?php
$subjects['body'] = "[b]Make Me Bold![/b]";
$subjects['subject'] = "[i]Make Me Italics![/i]";
$regex[] = "@\[b\](.*?)\[/b\]@i";
$regex[] = "@\[i\](.*?)\[/i\]@i";
$replacements[] = "<b>$1</b>";
$replacements[] = "<i>$1</i>";
$results = preg_replace($regex, $replacements, $subjects);
?>

When you execute the code shown above, you will end up with an array that looks like this:

<?php
array(2) {
   ["body"]=>string(20) "<b>Make Me Bold!</b>"
   ["subject"]=>string(23) "<i>Make Me Italic!</i>"
}
?>
⚠️ **GitHub.com Fallback** ⚠️