General Question

klaas4's avatar

Cut a string into pieces (PHP! ;-) )

Asked by klaas4 (2194points) 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

paulc's avatar

You could use substr while looping up to the length of the string and using array_push to build your $string_array.

klaas4's avatar

Oh, yeah, I’m not so good with loops too.
Would you be so nice to write it for me? Thanks.

paulc's avatar

Come to think of it you might be able to use:

explode(””, $example_string);

phoenyx's avatar

iirc, explode is what you want.

klaas4's avatar

Of course! That I didn’t think of that. Thanks!

klaas4's avatar

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.

paulc's avatar

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 :)

klaas4's avatar

Yep, it works. Thanks again.

richardhenry's avatar

Speaking of captchas, you might want to check out http://recaptcha.net/.

klaas4's avatar

I decided to use this not so very secure captcha, because it’s not an important form, so…
Thanks anyway.

Vincentt's avatar

You don’t want to use explode() but str_split().

$stringArray = str_split($string);

Answer this question

Login

or

Join

to answer.

This question is in the General Section. Responses must be helpful and on-topic.

Your answer will be saved while you login or join.

Have a question? Ask Fluther!

What do you know more about?
or
Knowledge Networking @ Fluther