preg_split

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • www.douglassdavis.com

    preg_split


    lets say I have a line of text with multiple spaces between each word..
    I am not sure how many spaces. I would like to take the line of text,
    and change it to put only one space between the words.

    So, my idea was to split it on the spaces, then implode it with one
    space between each word.

    But, this doesn't work:

    preg_split("/\\s*/","test test test test")

    I would think that the regular expression would match multiple spaces,
    and split on that, but instead it just breaks apart each character of
    the string.

    How can I break it apart so I get something like:

    Array (
    [0] => "test",
    [1] => "test",
    [2] => "test"
    )

  • Andrew @ Rockface

    #2
    Re: preg_split

    www.douglassdavis.com wrote:[color=blue]
    > lets say I have a line of text with multiple spaces between each word..
    > I am not sure how many spaces. I would like to take the line of text,
    > and change it to put only one space between the words.[/color]

    If you just want to replace multiple blanks between words try:
    $string = preg_replace("/\s+/", " ", $string);
    [color=blue]
    > So, my idea was to split it on the spaces, then implode it with one
    > space between each word.
    >
    > But, this doesn't work:
    >
    > preg_split("/\\s*/","test test test test")[/color]

    Replace * with +
    [color=blue]
    > I would think that the regular expression would match multiple spaces,
    > and split on that, but instead it just breaks apart each character of
    > the string.
    >
    > How can I break it apart so I get something like:
    >
    > Array (
    > [0] => "test",
    > [1] => "test",
    > [2] => "test"
    > )[/color]

    $array = preg_split("/\s+/",$string);

    --
    Andrew @ Rockface
    np: (Winamp is not active ;-)

    Comment

    • www.douglassdavis.com

      #3
      Re: preg_split


      Andrew @ Rockface wrote:[color=blue]
      > www.douglassdavis.com wrote:[color=green]
      > > lets say I have a line of text with multiple spaces between each word..
      > > I am not sure how many spaces. I would like to take the line of text,
      > > and change it to put only one space between the words.[/color]
      >
      > If you just want to replace multiple blanks between words try:
      > $string = preg_replace("/\s+/", " ", $string);
      >[/color]

      much better... thanks.
      [color=blue][color=green]
      > > So, my idea was to split it on the spaces, then implode it with one
      > > space between each word.
      > >
      > > But, this doesn't work:
      > >
      > > preg_split("/\\s*/","test test test test")[/color]
      >
      > Replace * with +[/color]

      I hadn't thought of that... makes sense.

      Comment

      Working...