在'-'之后和检测到','之后的所有内容都在字符串中停止并再次执行,如何?
substr everything after '-' and after detecting ',' in string stop and do it again, how?
我有一个看起来像这样的字符串:
earth-green, random-stuff, coffee-stuff, another-tag
我正在尝试删除“-”后面的所有内容,但是当检测到“,”或“”时,请停止并重做该过程,以便传出字符串变为
earth random coffee another
substr($func, 0, strrpos($func, '-'));
删除第一个“-”之后的所有内容
最简单的方法是使用 explode(通过按字符拆分将字符串转换为数组),因此按逗号拆分
然后对于该数组中的每一项,拆分连字符并取第一个元素。
然后您可以使用内爆(与爆炸相反)将项目粘合在一起[=13=]
这是假设没有多余的逗号或其他并发症
$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);
方法略有不同,使用 array_walk 和匿名函数来迭代而不是 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);
我有一个看起来像这样的字符串:
earth-green, random-stuff, coffee-stuff, another-tag
我正在尝试删除“-”后面的所有内容,但是当检测到“,”或“”时,请停止并重做该过程,以便传出字符串变为
earth random coffee another
substr($func, 0, strrpos($func, '-'));
删除第一个“-”之后的所有内容
最简单的方法是使用 explode(通过按字符拆分将字符串转换为数组),因此按逗号拆分
然后对于该数组中的每一项,拆分连字符并取第一个元素。
然后您可以使用内爆(与爆炸相反)将项目粘合在一起[=13=]
这是假设没有多余的逗号或其他并发症
$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);
方法略有不同,使用 array_walk 和匿名函数来迭代而不是 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);