Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 555
matthy Avatar asked Aug 18 '09 13:08

matthy


People also ask

Can I use foreach for string in PHP?

Approach 1: Using str_split() and foreach Take a string. Split the string into an array of characters using str_split() function. Use a looping statement like for loop or while loop, to iterate over each of the element (character) in the array.

How can I split a string into two parts in PHP?

PHP | explode() Function explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs.

How do I split a character in a string in PHP?

PHP | str_split() Function The str_split() is an inbuilt function in PHP and is used to convert the given string into an array. This function basically splits the given string into smaller strings of length specified by the user and stores them in an array and returns the array.


3 Answers

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.

like image 172
Tom Haigh Avatar answered Oct 03 '22 13:10

Tom Haigh


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

$chars = str_split($str);
foreach($chars as $char){
    // your code
}
like image 21
Kiyan Avatar answered Oct 03 '22 12:10

Kiyan


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 )
like image 43
Danijel Avatar answered Oct 03 '22 12:10

Danijel