Mecom
Mecom

Reputation: 411

Getting file name out of a string

I need to get the filename 'HomeModel' out of a string app\model\common\HomeModel. This is what I tried

First, replace '\' with '/' using the str_replace.

$model = 'app\model\common\HomeModel';
$file = str_replace("\\", '/', $model) . ".php";
echo $file;

the result

app/model/common/HomeModel.php

then I explode the result like so

$model = 'app\model\common\HomeModel';
$file = str_replace("\\", '/', $model) . ".php";
echo $file;

$result = explode("/", $file);
echo '<br>';
var_dump($result);

and then this is what I have

array (size=4)
  0 => string 'app' (length=3)
  1 => string 'model' (length=5)
  2 => string 'common' (length=6)
  3 => string 'HomeModel.php' (length=18)

Now, how do I get the last value 'HomeModel' out of this array for further use?, I need to assign the value 'HomeModel' to $class.

Upvotes: 0

Views: 196

Answers (5)

aslawin
aslawin

Reputation: 1981

You can try this approach:

<?php

$model = 'app\model\common\HomeModel';

$fileName = substr(str_replace("\\", '/',$model), strrpos(str_replace("\\", '/',$model),'/') + 1).'.php';

echo $fileName;

Upvotes: 0

Mohammed Alhanafi
Mohammed Alhanafi

Reputation: 886

Try this one,

$class = $result[count($result)-1];

Upvotes: 0

Ofir Baruch
Ofir Baruch

Reputation: 10346

While end() is the answer to this specific question, I would encourage other members to try a better approach regarding the case of breaking a path to its parts using the php function pathinfo().

$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
echo $path_parts['basename']; // since PHP 5.2.0. Output: lib.inc.php

In your example, just use the first str_replace so it would be a valid path and manually add the php extension to the string.

Upvotes: 2

splash58
splash58

Reputation: 26153

You can use pathinfo function

$file = str_replace("\\", '/', $model) . ".php";
echo pathinfo($file)['filename']; // HomeModel

Upvotes: 2

MCMXCII
MCMXCII

Reputation: 1026

end() should do the job.

$class = end($result);

Upvotes: 5

Related Questions