Page 1 of 1

Splitting text

Posted: Thu Dec 23, 2010 11:41 am
by adamyork
I have a text field that contains the following (example text used):

1_2_3_4__5__6

(I'm using underscores instead of spaces, as the forum keeps auto-correcting it on submit!)

As you can see the first few are split by a single space, with the last few numbers split by a double space.

My aim is to put each of these numbers into a table in a MYSQL database. But I'm having trouble breaking them up.

Re: Splitting text

Posted: Thu Dec 23, 2010 12:22 pm
by kristen
Why are some numbers split by single spaces and others by doubles?

Are they feeding in as a string or individual int?

And are they going into different cols in the DB?

It's possible to do what you want, but some context of why and how and for what reason would help. :wink:

Re: Splitting text

Posted: Thu Dec 23, 2010 12:32 pm
by adamyork
I'm basically copying and pasting a table full of data from another website into a text box (and then into my DB).

Not sure why some have 1 space and others have 2, that's just how it pastes!

Yes each will be a different column.

Re: Splitting text

Posted: Thu Dec 23, 2010 12:40 pm
by Jonah Bron

Code: Select all

$string = '1_2_3_4__5__6';
$numbers = explode('_', $string);
$numbers = array_filter($numbers);
print_r($numbers);
/*
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [5] => 5
    [7] => 6
)
*/
That will break it up by a single underscore, and then remove null values.

Re: Splitting text

Posted: Thu Dec 23, 2010 12:43 pm
by novice4eva
do a preg replace, replace two or more spaces by one space(should be possible). Rest is normal explode I guess.