1

たとえば、次のような文字列があります。

"abc b、bcd vr、cd deb"

この場合、すべてのポイントが「abc bcd cd」になるまで、この文字列の最初の単語を取得したいと思います。残念ながら、私のコードは機能しません。手伝って頂けますか?

<?php
$string= "abc b, bcd vr, cd deb";
$ay = explode(",", $string);
$num= count($ay); 
$ii= 0;
while ($ii!=$num){
$first = explode(" ", $ay[$ii]);
echo $first[$ii];
$ii= $ii+1;
} 
?>
4

4 に答える 4

1
<?php
function get_first_word($string)
{
    $words = explode(' ', $string);
    return $words[0];
}

$string = 'abc b, bcd vr, cd deb';
$splitted = explode(', ', $string);
$new_splitted = array_map('get_first_word', $splitted);

var_dump($new_splitted);
?>
于 2012-09-09T12:55:56.113 に答える
0
<?php
$string= "abc b, bcd vr, cd deb";
$ay = explode(",", $string);
$num= count($ay); 
$ii= 0;
while ($ii!=$num){
$first = explode(" ", $ay[$ii]);
echo ($ii == 0) ? $first[0] . " " : $first[1] . " ";
$ii= $ii+1;
} 
?>

最初の要素のスペースの前にある$first[$ii]ので、最初の要素を取得したときにのみ取る必要があります。explode

于 2012-09-09T12:55:42.663 に答える
0
$string= "abc b, bcd vr, cd deb";
$ay = explode(",", $string);
foreach($ay as $words) {
    $words = explode(' ', $words);
    echo $words[0];
} 
于 2012-09-09T12:56:48.037 に答える
0

使用array_reduce()

$newString = array_reduce(
    // split string on every ', '
    explode(", ", $string), 
    // add the first word of every comma section to the partial string  
    function(&$result, $item){

        $result .= array_shift(explode(" ", $item)) . " ";

        return $result;

    }
);
于 2012-09-09T13:07:49.667 に答える