2017-01-08 11 views
-2

普通の文字列関数でこれを行うことができますが、これがregexで実行できるかどうか疑問に思っています。正規表現と"/"の間の文字列からテキストと数字を抽出する

$list = array("animal","human","bird"); 

$input1 = "Hello, I am an /animal/1451/ and /bird/4455";  
$input2 = "Hello, I am an /human/4461451";  
$input3 = "Hello, I am an /alien/4461451"; 

$output1 = ["type"=>"animal","number"=>1451],["type"=>"bird","number"=>4455]];  
$output2 = [["type"=>"human","number"=>4461451]]; 
$output3 = [[]]; 

    function doStuff($input,$list){ 
     $input = explode(" ",$input); 
     foreach($input as $in){ 
      foreach($list as $l){ 
       if(strpos($in,"/".$l) === 0){ 
        //do substr to get number and store in array 
       } 
      } 
     } 
    } 
+0

「Write codes for me」の質問?あなたはすでに何かをしようとしていますか? –

+0

私は何を試して待っている更新する –

+0

私はタグで混乱している、それはPHPになると思いますか? JavaScript? – BrunoLM

答えて

0

ソリューション:

$regex = '~/(animal|human|bird)/(\d+)~'; 
$strs = [ 
    "Hello, I am an /animal/1451/ and /bird/4455", 
    "Hello, I am an /human/4461451", 
    "Hello, I am an /alien/4461451", 
]; 
$outs = []; 
foreach ($strs as $s) { 
    $m = []; 
    preg_match_all($regex, $s, $m); 
    // check $m structure 
    echo'<pre>',print_r($m),'</pre>' . PHP_EOL; 

    if (sizeof($m[1])) { 
     $res = []; 
     foreach ($m[1] as $k => $v) { 
      $res[] = [ 
       'type' => $v, 
       'number' => $m[2][$k], 
      ]; 
     } 
     $outs[] = $res; 
    } 
} 

echo'<pre>',print_r($outs),'</pre>'; 
+0

Genius u_mulderは今日、毎日 –

0

JavaScriptでは、あなたがpreg_match_allarray_map機能を使用して、この

var list = ["animal","human","bird"]; 
 

 
var input1 = "Hello, I am an /animal/1451/ and /bird/4455";  
 
var input2 = "Hello, I am an /human/4461451";  
 
var input3 = "Hello, I am an /alien/4461451"; 
 

 
function get(input) { 
 
    var regex = new RegExp('(' + list.join('|') + ')\/(\\d+)', 'g'); 
 
    var result = []; 
 
    var match; 
 

 
    while ((match = regex.exec(input))) { 
 
    result.push({ type: match[1], number: match[2] }); 
 
    } 
 
    
 
    return result; 
 
} 
 

 
console.log(
 
    get(input1), 
 
    get(input2), 
 
    get(input3) 
 
);

+0

を使用する正規表現のビット正規表現を学習しました。どちらか私は受け入れる必要があります私は知らない –

0

ショートソリューションのように行うことができます。

$pattern = "/\/(?P<type>(". implode('|', $list)."))\/(?P<number>\d+)/"; 
$result = []; 
foreach ([$input1, $input2, $input3] as $str) { 
    preg_match_all($pattern, $str, $matches, PREG_SET_ORDER); 
    $result[] = array_map(function($a){ 
     return ['type'=> $a['type'], 'number' => $a['number']]; 
    }, $matches); 
} 

print_r($result); 
+0

これもクールです –

関連する問題