[英]PHP preg_match how to grep string between underscores
I have this string: 我有这个字符串:
mctrn_25595_AdvandSurthree
and want to parse it to extract the number 25595
into one variable and basically anything behind 25595_
into another variable. 并要分析它提取数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");
The result from my command line: 我的命令行结果:
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
I am currently a PHP novice and yet failing to do "such simple stuff". 我目前是PHP的新手,但没有做“如此简单的事情”。
If you know that the string will always be in the form of mctrn_[some integers]_[a string of text] then you could possibly just use explode() and list() : 如果您知道该字符串将始终为mctrn_ [一些整数] _ [一个文本字符串]的形式,则可以使用explode()和list() :
$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");
Otherwise if you still want to use preg_match() , then you could try this: 否则,如果您仍然想使用preg_match() ,则可以尝试以下操作:
$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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.