Jump to content

Archived

This topic is now archived and is closed to further replies.

nick5449

separating words

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

Share this post


Link to post
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]

Share this post


Link to post
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]

Share this post


Link to post
Share on other sites

×

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.