Jump to content

need regex match for file.php?querystring


nikefido

Recommended Posts

This can find the file (doesn't even have to be a php file) in a string, even if that file is contained within subfolders. EDIT - This pattern assumes that the file name can contain any word characters (a-zA-Z0-9_), a space and a dash.. if spaces nor dashes will be in files, you can simply remove those from the pattern.

 

$file = '/someFolder/someOtherFolder/somefile.php?submit=dj';
$replace = 'someOtherFile';

$newFile = preg_replace('#[\w -]+(\.[^?]+)#', "$replace$1", $file);
echo $newFile;

 

Ouput:

/someFolder/someOtherFolder/someOtherFile.php?submit=dj

Since he has such a specific string, it would probably be better to use something like:

 

<?php
$string = 'somefile.php?submit=dj';
$file = array_shift(explode('?', $string));
echo $file;
?>

 

a) you only isolate the file... I *think* the OP wants to change the filename to something else (yet retain the query part?) Maybe I misunderstood what the OP seeks.

b) I have made the solution more 'adaptable', (just in case the OP tries to apply it to a string with subfolders). How many times have you provided a solution, only to have the OP come back and throw in a new situation and thus your solution no longer works (this is not your fault.. but rather the OP in question for not explaining ALL situations needed)? And this leads to point c...

c) Your solution would not work if there were 'all of a sudden' subfolders... I am seeing so many poorly constructed posed problems by OPs these days, I am trying to think of solutions that can solve some more 'unknowns' thrown into the mix.. may not be perfect.. but might solve a round or two of 'I tried your code against THIS, and it didn't work' kind of thing.

 

If I have misunderstood things, then my apologies. I gathered the filename is to be altered to something else, yet everything else in the string is retained.

Okay, subfolders:

 

<?php
$string = '/some/sub/dirs/somefile.php?submit=dj';
$file = array_shift(explode('?', basename($string)));
echo $file;
?>

Output: somefile.php

But don't get me wrong, I totally see your point.  Sometimes things are handled better without regex, like in this case.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.