在数组中的特定位置查找字符串 - PHP

问题描述 投票:0回答:4

我有以下文本字符串:“园艺,景观美化,足球,3D 建模”

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

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

这是我迄今为止的(蹩脚)尝试:

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

如有任何帮助,我们将不胜感激。

非常感谢

php regex string explode implode
4个回答
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
投票
//PHP 5.4
echo explode(',Football', $array)[0]

//PHP 5.3-
list($string) = explode(',Football', $array);
echo $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 不同。


0
投票

您可以避免将分隔字符串拆分为数组的行为,而只需使用正则表达式来提取搜索单词之前的单词。

您的示例搜索词实际上不需要

preg_quote()
,但如果该词来自不受信任的来源,则这是一个好主意。

代码:(演示

var_export(
    preg_match(
        '#[^,]+(?=,' . preg_quote($find) . ')#',
        $string,
        $m
    )
    ? $m[0]
    : null
);

如果未找到搜索词或没有前面的词,则返回

null
。如果您需要强制执行全字匹配,可以将
(?:$|,)
添加到前瞻末尾。

© www.soinside.com 2019 - 2024. All rights reserved.