在require行上的preg_replace

Trying to just keep the file name and remove all other characters.

require_once($GLOBALS['root'] . '/library/test/TestFactory.php');

Want it to look like this:

/library/test/TestFactory.php

So far have this

$string = "require_once($GLOBALS['root'] . '/library/test/TestFactory.php');"
$string = preg_replace("~^.*?(?=\/)~i", "", $string);

I get this but just missing the end characters of "');" Any help would be appreciated.

/library/test/TestFactory.php');

UPDATE, on another instance i get something like this but my regex won't read it well as it don't have a / in there.

require_once($_SERVER['DOCUMENT_ROOT'] . $this->config . 'display.php

I would think i would want just display.php

You can try the following for both of your cases.

$str = preg_replace('~^[^.]*\.[^\'"]*[\'"]([^\'"]+).*~m', '$1', $str);

Working Demo

If you want to use a regular expression, you will need to use a matching group to do the replacement.

$string = preg_replace("~[^/]*([^']*).*~i", '$1', $string);
  • [^/]* - all characters that are not a /
  • ([^']*) - matching group on all characters that are not a '
  • .* - the rest of the string

Test it on Regex101.

You can also grab the match instead of replace.

(\/.*\/[^']+)

Try this.See demo.

http://regex101.com/r/kP8uF5/8

$re = "~(/.*/[^']+)~i";
$str = "require_once(\$GLOBALS['root'] . '/library/test/TestFactory.php');";

preg_match_all($re, $str, $matches);

The below works assuming the file path consists of alphanumeric characters, forward slashes or periods. If not, you can just adjust it and add in any additional characters to this piece (\/[\w\/\.]+):

$string = "require_once(\$GLOBALS['root'] . '/library/test/TestFactory.php');";
$string = preg_replace("~^[^/]+(/[\w/\.]+).*~i", "$1", $string);
echo $string;

Note that I had to escape the dollar sign in your test string.