-1

I am not familiar with preg_replace function of php. I need to solve an issue by using this function.

My string is sidebarCond/none.php. I need to remove folder name whatever it is (like: sidebarCond/ or folder-name/) and also the extension (Like: .php or .html).

$sidebar = 'sidebarCond/none.php';
$sidebar = str_replace( 'sidebarCond/', '', $sidebar );
$sidebar = str_replace( '.php', '', $sidebar );

This is the code of how I solve my problem, but this is not a smart solution.

5
  • 1
    The solution to not being familiar with a function would be a link to the manual. Albeit, in this case, basename likely being the simpler alternative.
    – mario
    Jun 29, 2019 at 9:42
  • Do you have to use preg_replace? Or preg match if you would only match it? Jun 29, 2019 at 9:56
  • I need to the solution if the pattern is like 'sidebarCond/none.php'. @the-fourth-bird
    – Naf Rifat
    Jun 29, 2019 at 10:00
  • If the accepted answer works for you, I think that would be the best approach. Jun 29, 2019 at 10:06
  • It's working...
    – Naf Rifat
    Jun 29, 2019 at 18:23

1 Answer 1

2

Don't use string functions in this case. Use pathinfo

$sidebar = 'sidebarCond/none.php';
$sidebar = pathinfo($sidebar)['filename'];

OR

$sidebar = 'sidebarCond/none.php';
$sidebar = pathinfo($sidebar, PATHINFO_FILENAME);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.