-1

次のテキスト文字列があります: "Gardening,Landscaping,Football,3D Modelling"

「 Football 」というフレーズのの文字列を選択するには、PHP が必要です。

したがって、配列のサイズに関係なく、コードは常に「Football」というフレーズをスキャンし、その直前のテキストを取得します。

これまでの私の(不自由な)試みは次のとおりです。

$array = "Swimming,Astronomy,Gardening,Rugby,Landscaping,Football,3D Modelling";
$find = "Football";
$string = magicFunction($find, $array);
echo $string; // $string would = 'Landscaping'

これについての助けをいただければ幸いです。

どうもありがとう

4

3 に答える 3

2
//PHP 5.4
echo explode(',Football', $array)[0]

//PHP 5.3-
list($string) = explode(',Football', $array);
echo $string;
于 2012-12-18T16:43:36.793 に答える
2
$terms = explode(',', $array);
$index = array_search('Football', $terms);
$indexBefore = $index - 1;

if (!isset($terms[$indexBefore])) {
    trigger_error('No element BEFORE');
} else {
    echo $terms[$indexBefore];
}
于 2012-12-18T16:45:50.307 に答える
1
$array = array("Swimming","Astronomy","Gardening","Rugby","Landscaping","Football","3D" "Modelling");
$find = "Football";
$string = getFromOffset($find, $array);
echo $string; // $string would = 'Landscaping'

function getFromOffset($find, $array, $offset = -1)
{
    $id = array_search($find, $array);
    if (!$id)
        return $find.' not found';
    if (isset($array[$id + $offset]))
        return $array[$id + $offset];
    return $find.' is first in array';
}

1 つ前とは異なるオフセットを設定することもできます。

于 2012-12-18T16:50:54.463 に答える