2012-12-18 57 views
-1

我有以下的文本字符串:“园艺,园林绿化,足球,3D建模”查找字符串数组 - PHP

我需要PHP短语之前挑出来的字符串,“Football”。

因此,无论数组的大小,代码将始终扫描短语“Football”,并检索它之前的文本。

这里是我的(跛脚)试图至今:

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

任何帮助,将不胜感激。

非常感谢

+1

而且[你有什么尝试](http://whathaveyoutried.com)? – Havelock

+0

嗨:)我还没有尝试过任何东西,因为我有点不确定从哪里开始。 – michaelmcgurk

+0

这看起来像正规表达式的工作 –

回答

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]; 
} 
+0

现在就试试这个 - 谢谢! :-) – michaelmcgurk

+0

这工作很好 - 谢谢!!!!!!! – michaelmcgurk

+0

无法编码它自己:) –

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

//PHP 5.3- 
list($string) = explode(',Football', $array); 
echo $string; 
+0

非常感谢。我现在就试试这个。 – michaelmcgurk

+0

谢谢你。但是,它不会删除**之前的内容**“足球”这个短语。所以,我的$字符串变成了“游泳,天文,园艺,橄榄球,园林绿化”。有任何想法吗?谢谢。 – michaelmcgurk

+1

哦,通过“挑选”我认为你的意思是“得到”而不是“删除”。只需使用'[1]'或'list(,$ string)'。 –

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以前不同。