2017-01-08 176 views
-2

我可以用普通的字符串函数做到这一点,但万一我不知道这件事是否可以在正则表达式的方式完成。从“/”之间的字符串中提取文本和数字

$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

'为我写代码'问题?或者你已经尝试过一些东西? –

+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

天才u_mulder学会了lil位正则表达式今天将使用每天 –

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

这一个也很酷 –