给出了PHP preg_replace字符串路径

时间:2015-03-18 12:34:19

标签: php regex preg-replace

我在PHP中遇到了preg_replace函数的问题。我无法弄清楚模式和替代品。

我有两个字符串和一些代码:

    $dirname1 = 'hdadas/dasdad/dasd/period_1min';
    $dirname2 = 'hdadas/dasdad/dasd/period_1min/abcdrfg.php';

    $pieces1 = explode('/', $dirname1);
    $pieces2 = explode('/', $dirname2);

    $dirname1 = end($pieces1);  // output will be period_1min
    $dirname2 = end($pieces2); // output will be abcdrfg.php

    $output = preg_replace($pattern, $replacement, $dirname1); // or (..,..,$dirname2

    echo $output; // i need 1min(without period_) or abcdrfg (without .php)

UPD:

   function Cat($dirname)
   {
      $name = explode('/', $dirname);

      $pattern = ???;
      $replacement = ???;

      return preg_replace($pattern, $replacement, $dirname1);
    }

    print(Cat('hdadas/dasdad/dasd/period_1min'))); // output need 1min only
    print(Cat('hdadas/dasdad/dasd/period_1min/abcdrfg.php'))); // output  need abcdrfg only  

2 个答案:

答案 0 :(得分:2)

这应该适合你:

(这里我使用basename()仅获取路径的最后部分,然后使用pathinfo()获取没有扩展名的最后一部分。之后我只使用preg_replace()来用空字符串替换下划线之前的所有内容)

<?php

    $dirname1 = "hdadas/dasdad/dasd/period_1min";
    $dirname2 = "hdadas/dasdad/dasd/period_1min/abcdrfg.php";

    $dirname1 = pathinfo(basename($dirname1))["filename"];
    $dirname2 = pathinfo(basename($dirname2))["filename"];

    echo $output = preg_replace("/(.*)_/", "", $dirname1); 


?>

输出:

1min
abcdrfg

答案 1 :(得分:1)

这个正则表达式如何/^.+_|\.[^.]+$/

$dirname1 = 'hdadas/dasdad/dasd/period_1min';
$dirname2 = 'hdadas/dasdad/dasd/period_1min/abcdrfg.php';

$pieces1 = explode('/', $dirname1);
$pieces2 = explode('/', $dirname2);

$dirname1 = end($pieces1);  // output will be period_1min
$dirname2 = end($pieces2); // output will be abcdrfg.php

$output = preg_replace('/^.+_|\.[^.]+$/', '', $dirname1); // or (..,..,$dirname2
echo $output,"\n"; // i need 1min(without period_) or abcdrfg (without .php)

$output = preg_replace('/^.+_|\.[^.]+$/', '', $dirname2); // or (..,..,$dirname2
echo $output,"\n"; // i need 1min(without period_) or abcdrfg (without .php)

<强>输出:

1min
abcdrfg