尝试保留文件名并删除所有其他字符。
require_once($GLOBALS['root'] . '/library/test/TestFactory.php');
希望它看起来像这样:
/library/test/TestFactory.php
到目前为止还有这个
$string = "require_once($GLOBALS['root'] . '/library/test/TestFactory.php');"
$string = preg_replace("~^.*?(?=\/)~i", "", $string);
我得到了这个,但只是错过了“')的结尾字符;”任何帮助将不胜感激。
/library/test/TestFactory.php');
更新,在另一个实例上,我得到类似的东西,但我的正则表达式不会读得很好,因为它没有/在那里。
require_once($_SERVER['DOCUMENT_ROOT'] . $this->config . 'display.php
我想我只想要display.php
答案 0 :(得分:2)
如果要使用正则表达式,则需要使用匹配的组进行替换。
$string = preg_replace("~[^/]*([^']*).*~i", '$1', $string);
[^/]*
- 所有不是/
([^']*)
- 所有非'
.*
- 字符串的其余部分在Regex101上进行测试。
答案 1 :(得分:2)
您可以针对两种情况尝试以下操作。
$str = preg_replace('~^[^.]*\.[^\'"]*[\'"]([^\'"]+).*~m', '$1', $str);
答案 2 :(得分:1)
你也可以抓住比赛而不是替换。
(\/.*\/[^']+)
试试这个。看看演示。
http://regex101.com/r/kP8uF5/8
$re = "~(/.*/[^']+)~i";
$str = "require_once(\$GLOBALS['root'] . '/library/test/TestFactory.php');";
preg_match_all($re, $str, $matches);
答案 3 :(得分:1)
以下工作假设文件路径由字母数字字符,正斜杠或句点组成。如果没有,您只需调整它并在此(\/[\w\/\.]+)
:
$string = "require_once(\$GLOBALS['root'] . '/library/test/TestFactory.php');";
$string = preg_replace("~^[^/]+(/[\w/\.]+).*~i", "$1", $string);
echo $string;
请注意,我必须在测试字符串中转义美元符号。