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


How do I extract a specific name between slashes in php?

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

<>之前/一些/任何/网站/dev/工具/测试/媒体/upload.ini/一些/任何/网站/dev/工具/测试//add.ini等。之前

我如何从上面的两个链接中提取名称"media"answers"get"?我可能不得不使用正则表达式,但它看起来像什么?

使用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 )

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

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

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

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

对于这种简单的模式,我通常建议使用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);
演示