如何在php中的斜杠之间提取特定名称?

时间:2011-12-17 02:12:03

标签: php regex

假设我可能有一些存储在字符串中的目录......它们可能看起来像这样

/something/WHATEVER/websites/dev/tools/tests/media/upload.ini

/something/WHATEVER/websites/dev/tools/tests/get/add.ini

etc.

如何从这两个链接中提取名称“media”和“get”?我可能不得不使用正则表达式,但它会是什么样子?

3 个答案:

答案 0 :(得分:2)

使用php功能爆炸? http://php.net/manual/en/function.explode.php

$str="one  ,two  ,       three  ,  four    "; 
print_r(array_map('trim',explode(",",$str)));

Output:

Array ( [0] => one [1] => two [2] => three [3] => four )

答案 1 :(得分:1)

如果你想使用正则表达式,它可能看起来像这样

/([^/]+)/[^/]+$

即,

preg_match('`/([^/]+)/[^/]+$`',$fullpath,$matches)

$matches[1]将包含您的目录。

答案 2 :(得分:0)

我通常建议sscanf这样简单的模式:

$string = '/something/WHATEVER/websites/dev/tools/tests/media/upload.ini';
$format = '/something/WHATEVER/websites/dev/tools/tests/%[^/]';
$r = sscanf($string, $format, $name);

除此之外,还有标准的PHP dirname函数,以便在您需要更加动态的情况下提供帮助,例如:文件名的最后一个目录名:

$string = '/something/WHATEVER/websites/dev/tools/tests/media/upload.ini';
$reduce = explode('/', dirname($string));
$name = end($reduce);

Demo