Forum Moderators: coopster

Message Too Old, No Replies

preg_split - returning only the first two substrings

         

geckofuel

5:14 pm on Nov 7, 2003 (gmt 0)

10+ Year Member



Say I've got this string:

$sports="basketball,football,hockey,lacrosse,cricket";

Now say that I want to do a preg_split to return only the first two elements of this list "basketball football" How do I do it?

This is what I tried:

return preg_split (',', $sports, 2);

But it returned:

"basketball football hockey,lacrosse,cricket"

Any ideas?

RobinC

5:45 pm on Nov 7, 2003 (gmt 0)

10+ Year Member



You're telling it you only want to split the first two - [uk2.php.net ], try leaving out the limit and it should work as you want.

Robin

coopster

7:44 pm on Nov 7, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



list($value1, $value2) = explode(',', $string);

Xuefer

2:19 am on Nov 8, 2003 (gmt 0)

10+ Year Member



list($value1, $value2) = explode(',', $string, 2);

coopster

11:53 pm on Nov 9, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



This won't work Xuefer, you can't include the last parameter, limit. If limit is set, the returned array will contain a maximum of limit elements with the last element containing the rest of the string.

It would return:


print $value1; // basketball
print $value2; // football,hockey,lacrosse,cricket

Note, the same thing would occur if you used

preg_split
, even without the last parameter. The key here is twofold:
  1. Use the list [us3.php.net] language construct
  2. Do NOT specify the limit parameter (or if you do, make sure it is at least 1 larger than the total number of values you want returned).

You could use either function, explode or preg_split in this manner to achieve the results desired.

jamesa

5:15 am on Nov 10, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Off the top of my head (so check the syntax):

$sports="basketball,football,hockey,lacrosse,cricket";

preg_match("/^([^,]+),([^,]+)/", $sports, $matches);

$first_two = $matches[1] . " " . $matches[2];

-- or --

$allsports = explode($sports);

$first_two = $allsports[0] . " " . $allsports[1];

Xuefer

5:31 am on Nov 10, 2003 (gmt 0)

10+ Year Member



hrm,.. it was i misunderstanding
list($value1, $value2) = explode(',', $string, 3);
this should be the fastest way
using regexp