Jump to content


Photo

separating words


  • Please log in to reply
3 replies to this topic

#1 nick5449

nick5449
  • New Members
  • Pip
  • Newbie
  • 6 posts

Posted 11 July 2006 - 10:53 PM

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

#2 ShogunWarrior

ShogunWarrior
  • Members
  • PipPipPip
  • Advanced Member
  • 528 posts
  • LocationIreland

Posted 11 July 2006 - 11:02 PM

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);

Stripped will now contain:
Array
(
    [0] => Hello
    [1] => this is a comma
    [2] => separated
    [3] => string with
    [4] => comas!!
)

<a href="http://www.daviddora...nmedia.com/">My New Site/Blog</a> | <a href="http://www.daviddora...m/check/">Check your page for broken links/images/scripts</a>

Zend Certified Engineer
Follow me on Twitter: http://twitter.com/davidd

#3 effigy

effigy
  • Staff Alumni
  • Advanced Member
  • 3,600 posts
  • LocationIL

Posted 11 July 2006 - 11:05 PM

A little more concise, and it removes surrounding whitespace:

<?php
	$str = "Hello, this is a comma, separated, string with, comas!!";
	$array = preg_split('/\s*,\s*/', $str);
	echo '<pre>', print_r($array, true), '</pre>';
?>

Regexp | Unicode Article | Letter Database
/\A(e)?((1)?ff(?:(?:ig)?y)?|f(?:ig)?)\z/

#4 ShogunWarrior

ShogunWarrior
  • Members
  • PipPipPip
  • Advanced Member
  • 528 posts
  • LocationIreland

Posted 11 July 2006 - 11:07 PM

Nice one.
<a href="http://www.daviddora...nmedia.com/">My New Site/Blog</a> | <a href="http://www.daviddora...m/check/">Check your page for broken links/images/scripts</a>

Zend Certified Engineer
Follow me on Twitter: http://twitter.com/davidd




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users