【问题标题】:Find string at specific position in array - PHP在数组中的特定位置查找字符串 - PHP
【发布时间】:2012-12-18 16:41:23
【问题描述】:

我有以下文本字符串:"Gardening,Landscaping,Football,3D Modelling"

我需要 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


【解决方案1】:
$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;
    

    【讨论】:

    • 谢谢。但是,它不会删除短语“Football”BEFORE 的内容。所以,我的 $string 变成了Swimming,Astronomy,Gardening,Rugby,Landscaping。有任何想法吗?谢谢。
    • 哦,“挑选”我以为您的意思是“获取”而不是“删除”。只需使用[1] 或list(,$string)。
    【解决方案3】:
    $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 不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-06
      • 2019-05-31
      • 1970-01-01
      • 2022-01-24
      • 2013-08-21
      • 1970-01-01
      相关资源
      最近更新 更多