Jump to content

separating words


nick5449

Recommended Posts

I have a group of words that are separated by a comma.  Such as "blah, blahblah blah".  I want to separate everything before and after the comma into two separate variables and also without the comma in there.  Can someone point me in the right direction? Thanks for any help
Link to comment
Share on other sites

[code]
function strip_blanks($arr)
{
        foreach( $arr as $ki=>$val )
        {
                if(trim($val)=='')
                {unset($arr[$ki]);}
                else{$arr[$ki] = trim($val);}
        }return($arr);
}

//Replace String
$str = "Hello, this is a comma, separated, string with, comas!!";
$expl = explode(',',$str);
$stripped = strip_blanks($expl);
[/code]

Stripped will now contain:
[code]
Array
(
    [0] => Hello
    [1] => this is a comma
    [2] => separated
    [3] => string with
    [4] => comas!!
)
[/code]
Link to comment
Share on other sites

A little more concise, and it removes surrounding whitespace:

[code]<?php
$str = "Hello, this is a comma, separated, string with, comas!!";
$array = preg_split('/\s*,\s*/', $str);
echo '<pre>', print_r($array, true), '</pre>';
?>[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.