【问题标题】:PHP get everything in a string before underscorePHP在下划线之前获取字符串中的所有内容
【发布时间】:2014-07-09 18:39:45
【问题描述】:

我这里有这段代码:

$imagePreFix = substr($fileinfo['basename'], strpos($fileinfo['basename'], "_") +1);

这让我得到了下划线之后的所有内容,但我希望得到下划线之前的所有内容,我将如何调整此代码以获取下划线之前的所有内容?

$fileinfo['basename'] 等于'feature_00'

谢谢

【问题讨论】:

  • 在第一个下划线之后?如果你有多个下划线怎么办?

标签: php string substr strpos


【解决方案1】:

你应该简单地使用:

$imagePreFix = substr($fileinfo['basename'], 0, strpos($fileinfo['basename'], "_"));

我看不出有任何理由使用 explode 并创建额外的数组来获取第一个元素。

您也可以使用(在 PHP 5.3+ 中):

$imagePreFix = strstr($fileinfo['basename'], '_', true); 

【讨论】:

    【解决方案2】:

    如果您完全确定始终至少有一个下划线,并且您对第一个下划线感兴趣:

    $str = $fileinfo['basename'];
    
    $tmp = explode('_', $str);
    
    $res = $tmp[0];
    

    其他方法:

    $str = "this_is_many_underscores_example";
    
    $matches = array();
    
    preg_match('/^[a-zA-Z0-9]+/', $str, $matches);
    
    print_r($matches[0]); //will produce "this"
    

    (可能正则表达式模式需要调整,但就本示例而言,它工作得很好)。

    【讨论】:

      【解决方案3】:

      我认为最简单的方法是使用explode

      $arr = explode('_', $fileinfo['basename']);
      echo $arr[0];
      

      这会将字符串拆分为子字符串数组。数组的长度取决于有多少 _ 实例。例如

      "one_two_three"
      

      会被分解成一个数组

      ["one", "two", "three"] 
      

      这里是some documentation

      【讨论】:

        【解决方案4】:

        如果您想要您建议的类型的老派答案,您仍然可以执行以下操作:

        $imagePreFix = substr($fileinfo['basename'], 0, strpos($fileinfo['basename'], "_"));

        【讨论】:

          猜你喜欢
          • 2021-08-31
          • 1970-01-01
          • 2012-01-29
          • 2021-05-02
          • 2018-08-08
          • 2010-12-23
          • 1970-01-01
          • 2011-03-06
          • 1970-01-01
          相关资源
          最近更新 更多