我有以下文字字符串:“园艺,园林绿化,足球,3D建模”
我需要PHP在 之前选择字符串 “足球”。
因此,无论数组的大小如何,代码都会一直扫描短语“足球”,并在其前面检索文本。
到目前为止,这是我的(跛脚)尝试:
$array = "Swimming,Astronomy,Gardening,Rugby,Landscaping,Football,3D Modelling";
$find = "Football";
$string = magicFunction($find, $array);
echo $string; // $string would = 'Landscaping'
对此的任何帮助将不胜感激。
非常感谢
答案 0 :(得分:2)
//PHP 5.4
echo explode(',Football', $array)[0]
//PHP 5.3-
list($string) = explode(',Football', $array);
echo $string;
答案 1 :(得分: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];
}
答案 2 :(得分: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';
}
您还可以将偏移设置为与之前的偏移不同。