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

使用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 回答
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在第一个元素的空间之前使用这个 whan。

于 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 回答