NOVINKA: Najžiadanejšie rekvalifikačné kurzy teraz s 50% zľavou + kurz AI ZADARMO. Nečakaj, táto ponuka dlho nevydrží! Zisti viac:

PHP - substr

Trieda

Koreň \ Bez triedy

Metóda - substr

(PHP 4, PHP 5, PHP 7)

The function returns a part of the string (a substring) according to the given parameters.

Procedurálne

  • function substr (string $string, int $start, int $length) : string

Parametre

NázovDátový typPredvolená hodnotaPopis
$stringstring

The input string which part we want to be returned. It must be at least 1 character long.

$startint

The number specifying the starting position from which we want to extract the substring.

The parameter can be:

  • A positive number: The starting position is based from the start of the string.
  • A negative number: The starting position is bad from the end of the string and the next positions are in the right-to-left direction.
$lengthint

Specifies the length of the substring from the starting position (the second parameter) in the original string (the first parameter).

If the parameter is not set, the substring of the starting point till the end of the original string is returned.

If we enter the parameter as:

  • positive number - The substring will be of the given length or shorter and will start from the starting position.
  • negative number - The given number of characters will be omitted from the end of the string. The substring will start from the starting position. If we enter a number which will cause the end of the string to meet the starting position, false will be returned.

Mávratovej hodnoty

Vracia: string

Returns the specified part of the original string. If the returned string is empty ("") or the function failed to return a value, it returns false.

Príklady

In the example are shown the different outputs of the function according to the given parameters.

<?php
$text = "Chuck Norris counted to infinity - twice.";
echo substr($text, 5) . "<br>"; // Norris counted to infinity - twice.
echo substr($text, -20) . "<br>"; // to infinity - twice.
echo substr($text, 7, 12) . "<br>"; // orris counte
echo substr($text, 2, -10) . "<br>"; // uck Norris counted to infinit
echo substr($text, -20, 12) . "<br>"; // to infinity
echo substr($text, -17, -3) . "<br>"; // infinity - twi
echo substr($text, -17, -18) ? substr($text, -17, -18) . "<br>" : "Returns false <br>";
echo substr($text, 2, 0) ? substr($text, -17, -18) . "<br>" : "Returns false <br>";

Súvisiace manuály

      • function mb_substr (string $str, int $start, int $length = NULL, string $encoding = mb_internal_encoding()) : string
      • function preg_match (string $pattern, string $subject, array &$matches, int $flags = 0, int $offset = 0) : int
      • function trim (string $str, string $character_mask = \t\n\r\0\x0B) : string
      Aktivity