Home Backend Development PHP Tutorial Several programs about PHP substr() function

Several programs about PHP substr() function

Nov 11, 2017 am 11:02 AM
php substr program

What is the substr() function? The substr() function returns part of the string. There are many programs written with the PHP substr() function. This article mainly introduces several programs written with the PHP substr() function.

Syntax: substr(string,start,length).

string: required. Specifies a part of the string to be returned.

start: required. Specifies where in the string to begin. Positive number - starts at the specified position in the string; negative number - starts at the specified position from the end of the string; 0 - starts at the first character in the string.

charlist: optional. Specifies the length of the string to be returned. The default is until the end of the string. Positive number - returned from the position of the start parameter; negative number - returned from the end of the string.

Note: If start is a negative number and length is less than or equal to start, length is 0.

Program List: Negative start parameter

1    <?php    
2        $rest = substr("abcdef", -1);    // returns "f"    
3        echo $rest.&#39;<br />&#39;;    
4        $rest = substr("abcdef", -2);    // returns "ef"    
5        echo $rest.&#39;<br />&#39;;    
6        $rest = substr("abcdef", -3, 1); // returns "d"    
7        echo $rest.&#39;<br />&#39;;    
8    ?>
Copy after login

Program running result:

1 f

2 ef

3 d

Program List: Negative length parameter

starts from the start position. If length is a negative value, it starts counting from the end of the string. If substr("abcdef", 2, -1), it starts from c, and then -1 means to intercept to e, which means to intercept cde.

01    <?php    
02        $rest = substr("abcdef", 0, -1);  // returns "abcde"    
03        echo $rest.&#39;<br />&#39;;    
04        $rest = substr("abcdef", 2, -1);  // returns "cde"    
05        echo $rest.&#39;<br />&#39;;    
06        $rest = substr("abcdef", 4, -4);  // returns ""    
07        echo $rest.&#39;<br />&#39;;    
08        $rest = substr("abcdef", -3, -1); // returns "de"    
09        echo $rest.&#39;<br />&#39;;    
10    ?>
Copy after login

Program running results:

1 abcde

2 cde

3 de

Program List: Basic substr() function Usage

01    <?php    
02    echo substr(&#39;abcdef&#39;, 1);     // bcdef    
03    echo &#39;<br />&#39;;    
04    echo substr(&#39;abcdef&#39;, 1, 3);  // bcd    
05    echo &#39;<br />&#39;;    
06    echo substr(&#39;abcdef&#39;, 0, 4);  // abcd    
07    echo &#39;<br />&#39;;    
08    echo substr(&#39;abcdef&#39;, 0, 8);  // abcdef    
09    echo &#39;<br />&#39;;    
10    echo substr(&#39;abcdef&#39;, -1, 1); // f    
11    echo &#39;<br />&#39;;    
12    // Accessing single characters in a string    
13    // can also be achieved using "square brackets"    
14    $string = &#39;abcdef&#39;;    
15    echo $string[0];                 // a    
16    echo &#39;<br />&#39;;    
17    echo $string[3];                 // d    
18    echo &#39;<br />&#39;;    
19    echo $string[strlen($string)-1]; // f    
20    echo &#39;<br />&#39;;    
21    ?>
Copy after login

Program running results:

1 bcdef

2 bcd

3 abcd

4 abcdef

5 f  

6   a  

7 d  

8   f  

Program List: Remove suffix

01    <?php    
02    //removes string from the end of other    
03    function removeFromEnd($string, $stringToRemove)    
04    {    
05        // 获得需要移除的字符串的长度    
06        $stringToRemoveLen = strlen($stringToRemove);    
07        // 获得原始字符串的长度    
08        $stringLen = strlen($string);    
09    
10        // 计算出需要保留字符串的长度    
11        $pos = $stringLen - $stringToRemoveLen;    
12    
13        $out = substr($string, 0, $pos);    
14        return $out;    
15    }    
16    $string = &#39;nowamagic.jpg.jpg&#39;;    
17    $result = removeFromEnd($string, &#39;.jpg&#39;);    
18    echo $result;    
19    ?>
Copy after login

Program running result:

1 nowamagic.jpg

Program List: If the string is too long, only the beginning and end will be displayed, and the middle will be replaced by an ellipsis

01    <?php    
02    $file = "Hellothisfilehasmorethan30charactersandthisfayl.exe";    
03    function funclongwords($file)    
04    {    
05        if (strlen($file) > 30)    
06        {    
07            $vartypesf = strrchr($file,".");    
08            // 获取字符创总长度    
09            $vartypesf_len = strlen($vartypesf);    
10            // 截取左边15个字符    
11            $word_l_w = substr($file,0,15);    
12            // 截取右边15个字符    
13            $word_r_w = substr($file,-15);    
14            $word_r_a = substr($word_r_w,0,-$vartypesf_len);    
15            return $word_l_w."...".$word_r_a.$vartypesf;    
16        }    
17        else    
18            return $file;    
19    }    
20    // RETURN: Hellothisfileha...andthisfayl.exe    
21    $result = funclongwords($file);    
22    echo $result;    
23    ?>
Copy after login

Program operation result:

1 Hellothisfileha ...andthisfayl.exe

Program List: Display extra text as ellipses

Many times we need to display a fixed number of words, and the extra words are replaced with ellipses.

01    <?php    
02    $text = &#39;welcome to nowamagic, I hope you can find something you wanted.&#39;;    
03    $result = textLimit($text, 30);    
04    echo $result;    
05    function textLimit($string, $length, $replacer = &#39;...&#39;)    
06    {    
07        if(strlen($string) > $length)    
08        return (preg_match(&#39;/^(.*)\W.*$/&#39;, substr($string, 0, $length+1), $matches) ? $matches[1] : substr($string, 0, $length)) . $replacer;    
09    
10        return $string;    
11    }    
12    ?>
Copy after login

Program running result:

1 Welcome to nowamagic, I hope...

Program List: Format string

Sometimes we need Format strings, such as phone numbers.

01    <?php    
02    function str_format_number($String, $Format)    
03    {    
04        if ($Format == &#39;&#39;) return $String;    
05        if ($String == &#39;&#39;) return $String;    
06        $Result = &#39;&#39;;    
07        $FormatPos = 0;    
08        $StringPos = 0;    
09        while ((strlen($Format) - 1) >= $FormatPos)    
10        {    
11            //If its a number => stores it    
12            if (is_numeric(substr($Format, $FormatPos, 1)))    
13            {    
14                $Result .= substr($String, $StringPos, 1);    
15                $StringPos++;    
16            //If it is not a number => stores the caracter    
17            }    
18            else    
19            {    
20                $Result .= substr($Format, $FormatPos, 1);    
21            }    
22            //Next caracter at the mask.    
23            $FormatPos++;    
24        }    
25        return $Result;    
26    }    
27    // For phone numbers at Buenos Aires, Argentina    
28    // Example 1:    
29        $String = "8607562337788";    
30        $Format = "+00 0000 0000000";    
31        echo str_format_number($String, $Format);    
32        echo &#39;<br />&#39;;    
33    // Example 2:    
34        $String = "8607562337788";    
35        $Format = "+00 0000 00.0000000";    
36        echo str_format_number($String, $Format);    
37        echo &#39;<br />&#39;;    
38    // Example 3:    
39        $String = "8607562337788";    
40        $Format = "+00 0000 00.000 a";    
41        echo str_format_number($String, $Format);    
42        echo &#39;<br />&#39;;    
43    ?>
Copy after login

Program running result:

1 +86 0756 2337788

2 +86 0756 23.37788

3 +86 0756 23.377 a

A few simple PHP substr() function small programs, but we still need to understand them and keep up with the ideas to follow the clues and write better programs.

Related recommendations:

php substr() function processing detailed Chinese explanation

php substr() function string interception usage example explanation

Usage of php substr() function

Recommended 10 articles about php substr() function

php substr Chinese garbled solution

The above is the detailed content of Several programs about PHP substr() function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles