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

时间:2017-01-08 16:10:05

标签: javascript php arrays regex string

我可以使用普通的字符串函数执行此操作,但万一我想知道这件事是否可以用正则表达式方式完成。

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

3 个答案:

答案 0 :(得分: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>';

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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