Substr everything after '-' and after finding ',' in line stop and do it again, how?

I have a line that looks like this:

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

I'm trying to delete everything behind the "-" but when a "," or "" is found, stop and repeat the process so that the outgoing line becomes

Earth random coffee different

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

      

which removes everything after the first '-'

+3


source to share


2 answers


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

http://php.net/explode

then for each of the elements in that array, divide by a hyphen and take the first element.

you can then glue the elements together with implode (opposite to explosion)



http://php.net/implode

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

      

+3


source


A slightly different approach using array_walk with an anonymous function to iterate over 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);

      

+1


source







All Articles