冒号分隔的输出php数组

时间:2019-08-13 11:13:35

标签: arrays csv comma

我有输入文本,其字符串用分号分隔为 “ apple ^; ball ^ room ^ mouse ^ bat ^; cricket ^ news ^ man ^”

我对此没有太多想法,但是我用php尝试了一下,但没有得到预期的输出

    $myString = "apple^;ball^room^mouse^bat^;cricket^news^man^";
    $myArray = explode(';', $myString);
    print_r($myArray);

我想从字符串上方以单个变量的形式输出

苹果球板球

表示每个分号的插入符号前的第一个字符

1 个答案:

答案 0 :(得分:0)

通过使用一些PHP字符串和数组操作函数,您可以做到

$myString = "apple^;ball^room^mouse^bat^;cricket^news^man^";
$myArray = explode(';', $myString);

foreach ($myArray as &$a) {
    $p = strpos($a, '^');
    $a = substr($a,0,$p);
}
$str = implode(' ', $myArray);

echo 'Input was > ' . $myString . PHP_EOL;
echo 'Output is > ' . $str . PHP_EOL;

结果

Input was > apple^;ball^room^mouse^bat^;cricket^news^man^
Output is > apple ball cricket