PHP:将一个字符串拆分为一个数组 foreach char

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1293950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:55:31  来源:igfitidea点击:

PHP: Split a string in to an array foreach char

phparrayssplitpasswordsvalidation

提问by matthy

I am making a method so your password needs at least one captial and one symbol or number. I was thinking of splitting the string in to lose chars and then use preggmatch to count if it contains one capital and symbol/number.

我正在制作一种方法,因此您的密码至少需要一个大写字母和一个符号或数字。我正在考虑将字符串拆分为丢失字符,然后使用 preggmatch 来计算它是否包含一个大写和符号/数字。

however i did something like this in action script but can't figure out how this is called in php. i cant find a way to put every char of a word in a array.

但是我在动作脚本中做了类似的事情,但无法弄清楚在 php 中是如何调用的。我找不到将单词的每个字符放入数组的方法。

AS3 example

AS3 示例

    for(var i:uint = 0; i < thisWordCode.length -1 ; i++)
{
    thisWordCodeVerdeeld[i] = thisWordCode.charAt(i);
    //trace (thisWordCodeVerdeeld[i]);
}

Thanks, Matthy

谢谢,马蒂

回答by Tom Haigh

You can access characters in strings in the same way as you would access an array index, e.g.

您可以像访问数组索引一样访问字符串中的字符,例如

$length = strlen($string);
$thisWordCodeVerdeeld = array();
for ($i=0; $i<$length; $i++) {
    $thisWordCodeVerdeeld[$i] = $string[$i];
}

You could also do:

你也可以这样做:

$thisWordCodeVerdeeld = str_split($string);

However you might find it is easier to validate the string as a whole string, e.g. using regular expressions.

但是,您可能会发现将字符串作为整个字符串进行验证会更容易,例如使用正则表达式。

回答by Kiyan

you can convert a string to array with str_splitand use foreach

您可以使用str_split将字符串转换为数组并使用 foreach

$chars = str_split($str);
foreach($chars as $char){
    // your code
}

回答by Greg

You can access a string using [], as you do for arrays:

您可以像访问[]数组一样使用 访问字符串:

$stringLength = strlen($str);
for ($i = 0; $i < $stringLength; $i++)
    $char = $str[$i];

回答by Danijel

Since str_split()function is not multibyte safe, an easy solution to split UTF-8 encoded string is to use preg_split()with u (PCRE_UTF8)modifier.

由于str_split()函数不是多字节安全的,拆分 UTF-8 编码字符串的一个简单解决方案是使用preg_split()withu (PCRE_UTF8)修饰符。

preg_split( '//u', $str, null, PREG_SPLIT_NO_EMPTY )

回答by Technomad

A less readable, but better performing solution, when iterating over many strings, might be using issetto check the end of the string. This might be better performing because issetis a language construct and strlenis a function:

当迭代多个字符串时,可读性较差但性能更好的解决方案可能isset用于检查字符串的结尾。这可能会更好地执行,因为它isset是一种语言结构并且strlen是一个函数:

for ($i = 0; isset($value[$i]); $i++) {
    "do something here"
}

This questionshould provide more background.

这个问题应该提供更多的背景。