【问题标题】:Extracting text and number from string between "/"从“/”之间的字符串中提取文本和数字
【发布时间】:2017-01-08 16:10:04
【问题描述】:

我可以用普通的字符串函数做到这一点,但如果我想知道这件事是否可以用 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
              }
           } 
       }
   }

【问题讨论】:

  • Write codes for me 问题?或者你已经尝试过?
  • 即时更新等待我尝试了什么
  • 我被标签弄糊涂了,它应该是php吗? javascript?
  • 已更新,但我使用了很多循环
  • js 和 php any 都可以工作

标签: javascript php arrays regex string


【解决方案1】:

正则表达式的解决方案:

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

【讨论】:

  • 天才 u_mulder 今天学会了 lil bit 正则表达式,每天都会用到
【解决方案2】:

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

【讨论】:

  • 这也很棒。我不知道应该接受哪一个
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 2018-02-07
    • 2022-11-02
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    相关资源
    最近更新 更多