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

标签 php string

$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/

相关文章:

javascript - 在 div 中禁用 html

javascript - 在 Javascript 中可以选择字符串中的单词吗?

python - 在 Python 中使用 csv 文件使用字典计算字符串中的单词数

php - SQL_CALC_FOUND_ROWS 和 FOUND_ROWS 总是返回 1

php - mysqli_fetch_assoc()需要参数/调用成员函数bind_param()错误。如何获取并修复实际的mysql错误?

php - 在 cpanel 上启用 allow_url_fopen

python - 替换模式后字符串的最后部分

string - Prolog DCG 从字母数字字符构建/识别字符串

c++ - ctypes如何将字符串从python传递给c++函数,以及如何将字符串从c++函数返回给python

php - 创建表查询时出错