PHP – How to cut out part of a string using iconv_substr()?

PHPServer Side ProgrammingProgramming

In PHP, the iconv_substr() function is used to cut a portion of a specified string by the offset and length parameters. Suppose we have a string "helloWorld" and we want to cut and show only the string (llowo), then we will select it by using numbers from 2 to 5.

Syntax

string iconv_substr(str $string, int $offset, int $length, str $encoding)

Parameters

iconv_substr() accepts four parameters: $string, $offset, $length and $encoding.

  • $string− The $string parameter specifies the original string.

  • $offset− If the $offset parameter is non-negative, then the iconv_substr() function cuts the selected portion of the string from beginning at offset character, counting from zero. And if it is negative, then iconv_substr() function cuts out the portion beginning at the position, offset characters away from the end of the string.

  • $length− if the $length parameter is given and it is positive, then its return value will contain at most length characters of the portion which begins at offset.

  • $encoding− If the encoding parameter is absent or null, then the string is assumed to be in iconv.internal_encoding.

Return Values

The iconv_substr() function returns the portion of the string specified by the offset and length parameters. If the string is shorter than the offset characters, it will return False. If the string is exactly of the same length as the offset characters, then a null or empty string will be returned.

Example 1

iconv_substr() function without space reading

 Live Demo

<?php
   // Helloworld sting is used
   // To cut the selected portion from string
   //iconv_substr function is used
   $string = iconv_substr("HelloWorld!", 2, 7, "UTF-8");

   // It will returns the character from 2 to 7
   var_dump($string);
?>

Output

string(7) "lloWorl"

Example 2

iconv_substr() function with space reading

 Live Demo

<?php
   // Helloworld sting is used
   // To cut the selected portion from string
   //iconv_substr function is used
   $string = iconv_substr ("Hello World!", 2, 7, "UTF-8");

   // It will returns the character from 2 to 7
   var_dump($string);
?gt;

Output

string(7) "llo Wor"
raja
Published on 23-Aug-2021 08:15:30
Advertisements