PHP explode and trim the results? Writer #1, 2010-06-22 php.net – where I posted this Overview This is something that I used to use on this site before I went to WordPress. If you checked “view source” and looked at the meta keywords, you would notice a comma separated string. When programming, you may want to take a comma separated string and grab the values without grabbing the commas or spaces. After all “this” is not equal to “this “, is it? On this site, that is what generated the similar stories that are linked at the bottom. The meta tags are separated and compared to other meta tags in the database. If another post has that tag then a link to that post is placed on the page. (Not anymore. Wordpress is so much easier. 🙂 ) How To You can achieve this by first “exploding” the string on the comma. But if you aren’t careful, you’ll end up with results that have spaces where ever your original string had a space. To get rid of this, simply loop through your results, trim the space, and place the outcome back into the original position of the original array. Code // Set your array using explode $meta_keys_arr = explode(",",$META_KEY); // replace the position with a // trimmed version of the string foreach($meta_keys_arr as $k=>$v){ $meta_keys_arr[$k] = trim($v); } PHP Programming explodephptrim
Variant: $str = “val1 , val2, val3 , val5,val7 “; $b = preg_split(‘/[ ]*,[ ]*/’, trim($str)); var_dump($b); //yields array(5) { [0]=> string(4) “val1” [1]=> string(4) “val2” [2]=> string(4) “val3” [3]=> string(4) “val5” [4]=> string(4) “val7” } Reply
A variant: string(4) “val1” [1]=> string(4) “val2” [2]=> string(4) “val3” [3]=> string(4) “val5” [4]=> string(4) “val7” } Reply