gpt4 book ai didi

PHP:如何获取字符串的字符一一

转载 作者:行者123 更新时间:2023-12-03 15:46:52 25 4
gpt4 key购买 nike

$str = "8560841836";
$mystr = array($str);
$string = strlen($str);
for($i=0; $i<=$string; $i++){ echo $string[$i]."\n"; }

此代码在一行中打印此字符串,但我希望在一行中的一个字符中打印此字符串,依此类推...

最佳答案

the PHP documentation:

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose. The functions substr() and substr_replace() can be used when you want to extract or replace more than 1 character.

Note: Strings may also be accessed using braces, as in $str{42}, for the same purpose.

Warning Internally, PHP strings are byte arrays. As a result, accessing or modifying a string using array brackets is not multi-byte safe, and should only be done with strings that are in a single-byte encoding such as ISO-8859-1.



例子:

// Get the first character of a string
$str = 'This is a test.';
$first = $str[0]; // 't'

// Get the third character of a string
$third = $str[2]; // 'i'

// Get the last character of a string.
$str = 'This is still a test.';
$last = $str[strlen($str)-1]; // '.'

// Modify the last character of a string
$str = 'Look at the sea';
$str[strlen($str)-1] = 'e'; // 'Look at the see'

因此,在您的情况下,这非常简单:

$str = '8560841836';
$len = strlen($str);

for($i = 0; $i < $len; ++$i) // < and not <=, cause the index starts at 0!
echo $str[$i]."\n";

关于PHP:如何获取字符串的字符一一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23405616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com