split keywords into array

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Geoff Berrow

    split keywords into array

    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/
  • Rik

    #2
    Re: split keywords into array

    On Tue, 24 Jul 2007 18:11:53 +0200, Geoff Berrow <blthecat@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

    Comment

    • Geoff Berrow

      #3
      Re: split keywords into array

      Message-ID: <op.tvy9w7siqnv 3q9@metalliumfr om 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/

      Comment

      • Rik

        #4
        Re: split keywords into array

        On Tue, 24 Jul 2007 19:12:53 +0200, Geoff Berrow <blthecat@ckdog .co.uk
        wrote:
        Message-ID: <op.tvy9w7siqnv 3q9@metalliumfr om 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

        Comment

        Working...