68

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

Robert Greiner
  • 29,049
  • 9
  • 65
  • 85
matthy
  • 8,144
  • 10
  • 38
  • 47

5 Answers5

95

you can convert a string to array with str_split and use foreach

$chars = str_split($str);
foreach($chars as $char){
    // your code
}
Kiyan
  • 2,155
  • 15
  • 15
81

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.

Tom Haigh
  • 57,217
  • 21
  • 114
  • 142
  • Documentation for square bracket notation: http://php.net/manual/en/language.types.string.php#language.types.string.substr – Pang Oct 23 '15 at 10:58
  • 1
    use isset instead of strlen: `for ($i=0; isset($string[$i]); $i++) {` – Melo Waste Jun 05 '17 at 15:59
  • $thisWordCodeVerdeeld = str_split($string); This is perfect answer for separating string characters and getting each of them in an array. – Umar Niazi May 16 '19 at 20:09
16

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 )
Danijel
  • 12,408
  • 5
  • 38
  • 54
15

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

$stringLength = strlen($str);
for ($i = 0; $i < $stringLength; $i++)
    $char = $str[$i];
nneonneo
  • 171,345
  • 36
  • 312
  • 383
Greg
  • 316,276
  • 54
  • 369
  • 333
  • 3
    this doesn't work correctly for multibyte string like: 'éléphant'. http://stackoverflow.com/questions/3666306/how-to-iterate-utf-8-string-in-php – David Silva Smith Jan 08 '17 at 14:20
1

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>";}
?>
chro
  • 11
  • 3