Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

str_replace wildcard or RegExp
Is there some kind of php regular expression that will target and replace the file name below. ie, replace any file name whether it be 'index.php' or 'about.php' or 'foofoo.php' ?
<?php echo str_replace('ANYTHING.php', '', $path ; ?>
1 Answer

Randy Hoyt
Treehouse Guest TeacherYes, there is a way to do it. Regular expressions are a bit of a black art and usually take me a few tries to get it right. You want to use the function preg_replace()
. This would be my first crack at it:
<?php
$string = '/path/to/folder/anything.php';
$pattern = '/\/[^\/]+\.php/';
$replacement = '/replacement.php';
echo preg_replace($pattern, $replacement, $string);
?>
Here's what I'm trying to accomplish (but regular expressions always need a bit of trial and error):
- The $pattern says (at least I tried to make it say) "find every occurrence of a slash followed by one or more characters that are not a slash followed by a dot-p-h-p."
- The $replacement says "replace any occurrence of that pattern with the following: slash-r-e-p-l-a-c-e-m-e-n-t-dot-p-h-p."
Does that help at all?