簡體   English   中英

平整正則表達式數組

[英]Flatten array of regular expressions

我有一個正則表達式-$ toks數組:

Array
(
    [0] => /(?=\D*\d)/
    [1] => /\b(waiting)\b/i
    [2] => /^(\w+)/
    [3] => /\b(responce)\b/i
    [4] => /\b(from)\b/i
    [5] => /\|/
    [6] => /\b(to)\b/i
)

當我嘗試展平時:

$patterns_flattened = implode('|', $toks); 

我得到一個正則表達式:

/(?=\D*\d)/|/\b(waiting)\b/i|/^(\w+)/|/\b(responce)\b/i|/\b(from)\b/i|/\|/|/\b(to)\b/i

當我嘗試:

if (preg_match('/'. $patterns_flattened .'/', 'I'm waiting for a response from', $matches)) {
    print_r($matches);  
}
  • 我收到一個錯誤:

    警告:preg_match():... index.php中的未知修飾符'('

我的錯誤在哪里? 謝謝。

您需要刪除開始和結束斜杠,如下所示:

$toks = [
    '(?=\D*\d)',
    '\b(waiting)\b',
    '^(\w+)',
    '\b(response)\b',
    '\b(from)\b',
    '\|',
    '\b(to)\b',
];

然后,我想您將要使用preg_match_all而不是preg_match

$patterns_flattened = implode('|', $toks);
if (preg_match_all("/$patterns_flattened/i", "I'm waiting for a response from", $matches)) {
    print_r($matches[0]);
}

如果得到第一個元素而不是所有元素,它將返回每個正則表達式的全部匹配項:

Array
(
    [0] => I
    [1] => waiting
    [2] => response
    [3] => from
)

在3v41.org上嘗試

   <?php

$data = Array
(
0 => '/(?=\D*\d)/',
1 => '/\b(waiting)\b/i',
2 => '/^(\w+)/',
3 => '/\b(responce)\b/i',
4 => '/\b(from)\b/i',
5 => '/\|/',
6 => '/\b(to)\b/i/'
);


$patterns_flattened = implode('|', $data);

$regex = str_replace("/i",'',$patterns_flattened);
$regex = str_replace('/','',$regex);

if (preg_match_all(  '/'.$regex.'/', "I'm waiting for a responce from", $matches)) {
    echo '<pre>';
print_r($matches[0]);
}

您必須從正則表達式以及i參數中刪除斜杠以使其起作用。 這就是它破裂的原因。

真正驗證您的正則表達式的一個非常好的工具是:

https://regexr.com/

當我必須比平常的正則表達式更大時,我總是使用它。

上面代碼的輸出是:

  Array
(
    [0] => I
    [1] => waiting
    [2] => responce
    [3] => from
)

$tok數組需要進行一些調整。

  1. 要消除該錯誤,您需要從每個數組元素中除去圖案定界符和圖案修飾符。
  2. 捕獲分組都不是必需的,實際上,這將導致更高的步數並造成不必要的輸出數組膨脹。
  3. 無論您打算使用(?=\\D*\\d) ,都需要重新考慮。 如果輸入字符串中的任何地方都有數字,則可能會生成很多空元素,這肯定不會對您的項目有任何好處。 看看會發生什么 ,當我把一個空間,然后1后, from您的輸入字符串。

這是我的建議:( PHP Demo

$toks = [
    '\bwaiting\b',
    '^\w+',
    '\bresponse\b',
    '\bfrom\b',
    '\|',
    '\bto\b',
];

$pattern = '/' . implode('|', $toks) . '/i';
var_export(preg_match_all($pattern, "I'm waiting for a response from", $out) ? $out[0] : null);

輸出:

array (
  0 => 'I',
  1 => 'waiting',
  2 => 'response',
  3 => 'from',
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM