简体   繁体   English

如何使用php从文件路径中获取目录名

[英]How to get directory name from file path using php

I am trying to get dir name from my file path: Currently below is my output:我正在尝试从我的文件路径中获取目录名称:目前以下是我的输出:

Array
(
    [path] => \documentLibrary\work\marketingProcess\BusinessMarketing\Design\Images\02_Product_Images\04_SHORT-RANGE\NINA\01_NINA-B1\source_WEB
)

and I want to get second last name which is (01_NINA-B1).我想获得第二个姓氏(01_NINA-B1)。 What I am trying is:我正在尝试的是:

 echo "<pre>".print_r(dirname($results),true)."</pre>"; die;

when I add dirname above it displays nothing.当我在上面添加 dirname 时,它​​什么也不显示。 What can I try next?我接下来可以尝试什么?

     $query = db_select('network_drive','networkd');
     $query
    ->fields('networkd', array('path'))
    ->condition('ndid',$networkdriveid,'=')
    ->orderBy('networkd.ndid');
    $results = $query->execute();
    echo "<pre>".print_r(dirname($results['path']),true)."</pre>"; die;

This looks like a plain string operation:这看起来像一个普通的字符串操作:

  1. split the string拆分字符串
  2. get the desired element得到想要的元素

Maybe like this:也许是这样的:

$s = '/documentLibrary/work/marketingProcess/BusinessMarketing/Design/Images/02_Product_Images/04_SHORT-RANGE/NINA/01_NINA-B1/source_WEB';

$a = explode(DIRECTORY_SEPARATOR, dirname($s)); //removes source_WEB and splits the string

echo array_pop($a); //gets the last element '01_NINA-B1'

Demo演示

Is this drupal?这是drupal吗? from my research I found out that db_select is a drupal function.从我的研究中我发现 db_select 是一个 drupal 函数。

Can you try this one?你能试试这个吗? it will attempt to explode the path string and find the second last element, if none is found it will return "N/A"它将尝试分解路径字符串并找到倒数第二个元素,如果没有找到,它将返回“N/A”

 $query = db_select('network_drive','networkd');
 $query
->fields('networkd', array('path'))
->condition('ndid',$networkdriveid,'=')
->orderBy('networkd.ndid');
$results = $query->execute();
foreach($results as $result){ 
    $array = explode("\\", $result->path);
    echo isset($array[count($array) - 2]) ? $array[count($array) - 2] : "N/A";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM