Cut a string into pieces (PHP! ;-) )
Asked by
klaas4 (
2194)
May 1st, 2008
I have a random string of 8 characters, always, and I want to split it in 8 arrays with one character each. So for example the string is = “YMy32fJu”, so I want this:
$string_array[0] = “Y”;
$string_array[1] = “M”;
$string_array[2] = “y”;
$string_array[3] = “3”;
$string_array[4] = “2”;
$string_array[5] = “f”;
$string_array[6] = “J”;
$string_array[7] = “u”;
How do you do this? It’s probably very simple, but I don’t have so much knowledge about arrays.
Davey
Observing members:
0
Composing members:
0
11 Answers
You could use substr while looping up to the length of the string and using array_push to build your $string_array.
Oh, yeah, I’m not so good with loops too.
Would you be so nice to write it for me? Thanks.
Come to think of it you might be able to use:
explode(””, $example_string);
Of course! That I didn’t think of that. Thanks!
Now I have this:
$email_text = randomcode(1,8,false); //is a function to generate a random code
$email = explode(””, $email_text);
echo ($email[0].$email[1]. ”<del>” .$email[2].$email[3].$email[4]. ”*” .$email[5].$email[6]. ”</del>” .$email[7]);
But it gives me the random code, and then <del>*</del>
after that, not in between the characters. What am I doing wrong?
Stupid textile. <del> is an -.
This is the page: http://ole.daveyyzermans.nl/images/captcha.php. I’m trying to make a kind-of captcha.
Then you may need to loop. I don’t have PHP installed and I’m a bit rusty but I’ll give it a try:
$length = strlen($email_text);
$email = array();
for ($c = 0; $c < $length; $c++) {
array_push($email, substr($email_text, $c, 1));
}
On a side note, they really need block code formatting here on Fluther :)
Yep, it works. Thanks again.
I decided to use this not so very secure captcha, because it’s not an important form, so…
Thanks anyway.
You don’t want to use explode() but str_split().
$stringArray = str_split($string);
Answer this question
This question is in the General Section. Responses must be helpful and on-topic.