简体   繁体   English

从“/”之间的字符串中提取文本和数字

[英]Extracting text and number from string between "/"

I can do this with normal string functions but in case i wonder if this thing can be done in regex way.我可以用普通的字符串函数来做到这一点,但万一我想知道这件事是否可以用正则表达式来完成。

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

Solution with regex:正则表达式解决方案:

$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>';

In JavaScript you can do like this在 JavaScript 中你可以这样做

 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) );

Short solution using preg_match_all and array_map functions:使用preg_match_allarray_map函数的简短解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM