Bent
Bent

Reputation: 1385

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.

$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".

Upvotes: 1

Views: 429

Answers (1)

Sᴀᴍ Onᴇᴌᴀ
Sᴀᴍ Onᴇᴌᴀ

Reputation: 8297

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():

$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:

$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");
}

Upvotes: 1

Related Questions