我有这个字符串:
mctrn_25595_AdvandSurthree
并希望解析它以将数字25595
提取到一个变量中,基本上将25595_
后面的任何内容提取到另一个变量中。
$scriptBasename = $_SERVER['SCRIPT_FILENAME'];
$scriptBasename = basename($scriptBasename);
$cuttedName = preg_replace( '/^mctrn_/', '' , $scriptBasename );
$port= preg_match('/[0-9]+/','',$scriptBasename);
$serverName= preg_match('/_"(.*)/','',$cuttedName);
echo($scriptBasename."\r\n");
echo($port."\r\n");
echo($serverName."\r\n");
我命令行的结果:
php mctrn_25595_AdvandSurthree.php <<< script filename!
PHP Notice: Array to string conversion in /home/bent/Downloads/mctrn_25595_AdvandSurthree.php on line 8
Array
0
0
我目前是一名PHP新手,却未能做出“如此简单的事情”。
答案 0 :(得分:1)
如果您知道该字符串将始终采用 mctrn_ [某些整数] _ [一串文本] 的形式,那么您可以使用explode()和{{3 }}:
$scriptBasename = $_SERVER['SCRIPT_FILENAME'];
$scriptBasename = basename($scriptBasename);
list($mctrn,$port,$serverName) = explode('_',$scriptBasename);
echo($scriptBasename."\r\n");
echo($port."\r\n");
echo($serverName."\r\n");
否则,如果你仍然想使用list(),那么你可以试试这个:
$scriptBasename = $_SERVER['SCRIPT_FILENAME'];
$scriptBasename = basename($scriptBasename);
preg_match('#\_(\d+)+\_(\w+)#',$scriptBasename,$matches);
if (count($matches) > 1) {
$port = $matches[1];
$serverName = $matches[2];
echo($scriptBasename."\r\n");
echo($port."\r\n");
echo($serverName."\r\n");
}