Splitting text

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
adamyork
Forum Newbie
Posts: 4
Joined: Mon Nov 29, 2010 7:24 am

Splitting text

Post 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.
kristen
Forum Newbie
Posts: 14
Joined: Tue Sep 07, 2010 5:51 pm

Re: Splitting text

Post 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:
adamyork
Forum Newbie
Posts: 4
Joined: Mon Nov 29, 2010 7:24 am

Re: Splitting text

Post 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.
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Splitting text

Post 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.
User avatar
novice4eva
Forum Contributor
Posts: 327
Joined: Thu Mar 29, 2007 3:48 am
Location: Nepal

Re: Splitting text

Post by novice4eva »

do a preg replace, replace two or more spaces by one space(should be possible). Rest is normal explode I guess.
Post Reply