'PHP: Split a string in to an array foreach char
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.
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.
AS3 example
for(var i:uint = 0; i < thisWordCode.length -1 ; i++)
{
thisWordCodeVerdeeld[i] = thisWordCode.charAt(i);
//trace (thisWordCodeVerdeeld[i]);
}
Thanks, Matthy
Solution 1:[1]
you can convert a string to array with str_split and use foreach
$chars = str_split($str);
foreach($chars as $char){
// your code
}
Solution 2:[2]
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.
preg_split( '//u', $str, null, PREG_SPLIT_NO_EMPTY )
Solution 3:[3]
You can access a string using [], as you do for arrays:
$stringLength = strlen($str);
for ($i = 0; $i < $stringLength; $i++)
$char = $str[$i];
Solution 4:[4]
Try this, It works beter for UTF8 characters (Kurdish, Persian and Arabic):
<?php
$searchTerm = "?????";
$chars = preg_split("//u", $searchTerm, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach($chars as $char){echo $char."<br>";}
?>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kiyan |
| Solution 2 | Danijel |
| Solution 3 | nneonneo |
| Solution 4 | chro |
