php strings have subscripts. In PHP, subscripts can be applied not only to arrays and objects, but also to strings. You can use the subscripts and square brackets "[]" of the string to access the character at the specified index position and read and write the character. Syntax "string name [subscript value]"; the subscript value (index value) of the string can only be an integer type, and the starting value is 0.
The operating environment of this tutorial: Windows 7 system, PHP version 7.1, DELL G3 computer
php strings have subscripts.
In PHP, subscripts can be applied not only to arrays and objects, but also to strings.
In PHP, you can use the subscript of the string and the square brackets "[]" to access the character at the specified index position and read and write the character. The left side of the brackets is the string name, and the brackets are the string subscript:
字符串名[下标值]
The subscript (index value) can only be an integer type, and the starting value is 0 (string subscript Counting starts from 0).
Example 1: Output the characters at the specified position
<?php header('content-type:text/html;charset=utf-8'); $str = "hello"; echo $str."<br>"; echo $str[0]."<br>"; echo $str[1]."<br>"; echo $str[2]."<br>"; ?>
Example 2: Modify the characters at the specified position
<?php header('content-type:text/html;charset=utf-8'); $str = "hello"; echo "原字符串:".$str."<br>"; $str[0]="H"; echo "修改第一个字符后:".$str."<br>"; ?>
Note: This method is suitable for English characters. Chinese characters occupy multiple character lengths and cannot be accurately positioned using subscripts.
<?php header('content-type:text/html;charset=utf-8'); $a = "我是123"; $a[1] = "5"; echo $a; //会出现乱码 ?>
Because Hanzi occupies 3 characters in length under UTF-8 encoding, when one character is replaced, the subsequent display will be garbled.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of Does php string have subscripts?. For more information, please follow other related articles on the PHP Chinese website!