By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,747 Members | 1,672 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,747 IT Pros & Developers. It's quick & easy.

split keywords into array

P: n/a
Does anyone know what regular expression I would use to split text into
an array, assuming the text can be separated by any non alphanumeric
character?

e.g

$string ="cat,dog fish, mouse -elephant/tiger";

would give

Array
(
[0] =cat
[1] =dog
[2] =fish
[3] =mouse
[4] =elephant
[5] =tiger
)
--
Geoff Berrow (put thecat out to email)
It's only Usenet, no one dies.
My opinions, not the committee's, mine.
Simple RFDs http://www.ckdog.co.uk/rfdmaker/
Jul 24 '07 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Rik
On Tue, 24 Jul 2007 18:11:53 +0200, Geoff Berrow <bl******@ckdog.co.uk
wrote:
Does anyone know what regular expression I would use to split text into
an array, assuming the text can be separated by any non alphanumeric
character?
$array = preg_split('/\W+/',$string,-1,PREG_SPLIT_NO_EMPTY);

\W = non-word character

"A "word" character is any letter or digit or the underscore character,
that is, any character which can be part of a Perl "word". The definition
of letters and digits is controlled by PCRE's character tables, and may
vary if locale-specific matching is taking place. For example, in the "fr"
(French) locale, some character codes greater than 128 are used for
accented letters, and these are matched by \w."

--
Rik Wasmus
Jul 24 '07 #2

P: n/a
Message-ID: <op.tvy9w7siqnv3q9@metalliumfrom Rik contained the
following:
>
>Does anyone know what regular expression I would use to split text into
an array, assuming the text can be separated by any non alphanumeric
character?

$array = preg_split('/\W+/',$string,-1,PREG_SPLIT_NO_EMPTY);
Thanks Rik. :-)
--
Geoff Berrow (put thecat out to email)
It's only Usenet, no one dies.
My opinions, not the committee's, mine.
Simple RFDs http://www.ckdog.co.uk/rfdmaker/
Jul 24 '07 #3

P: n/a
Rik
On Tue, 24 Jul 2007 19:12:53 +0200, Geoff Berrow <bl******@ckdog.co.uk
wrote:
Message-ID: <op.tvy9w7siqnv3q9@metalliumfrom Rik contained the
following:
>>
>>Does anyone know what regular expression I would use to split text into
an array, assuming the text can be separated by any non alphanumeric
character?

$array = preg_split('/\W+/',$string,-1,PREG_SPLIT_NO_EMPTY);

Thanks Rik. :-)

No problem.
BTW, if you also want to split on the underscore:
$array = preg_split('/(\W|_)+/',$string,-1,PREG_SPLIT_NO_EMPTY);
--
Rik Wasmus
Jul 24 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.