在' - '之后检测','并在字符串停止后再次执行它,怎么做?

I have a string looking like this:

earth-green, random-stuff, coffee-stuff, another-tag

I'm trying to remove everything behind the '-', but when ',' or ' ' is detected, stop and redo the process so the outgoing string becomes

earth random coffee another

substr($func, 0, strrpos($func, '-'));

that removes everything after first '-'

easiest way to do this is use the explode (convert a string into array by splitting on a character), so split on comma

http://php.net/explode

then for each of the items in that array, split on the hyphen and take the first element.

you can then glue items back together with implode (opposite of explode)

http://php.net/implode

this assumes that there are no extraneous commas or other complications

$str = 'earth-green, random-stuff, coffee-stuff, another-tag';
$arr = explode(',', $str);
$out_arr = array();  // will put output values here

foreach ($arr as $elem) {
  $elem = trim($elem); // get rid of white space)
  $arr2 = explode('-', $elem);
  $out_arr[] = $arr2[0]; // get first element of this split, add to output array
}

echo implode(' ', $out_arr);

Slightly different approach, using array_walk with an anonymous function to iterate rather than foreach.

<?php
$str = 'earth-green, random-stuff, coffee-stuff, another-tag';
$arr = explode(',', $str);
array_walk($arr, function( &$value, $index ) {
    $sub = explode('-', trim($value));
    $value = $sub[0];
});
var_dump($arr);