PHP 7 中的 Preg_replace_callback_array()


PHP 7 中的 Preg_replace_callback_array() 函式表示正則表示式,並替換了回撥的使用。此函式返回一個字串或字串陣列,以匹配一組正則表示式並使用回撥函式替換它們。

語法

preg_replace_callback_array(patterns, input, limit, count)

引數值

  • pattern − 它需要一個關聯陣列來將正則表示式模式與回撥函式關聯。
  • input/subject − 它需要一個字串陣列來執行替換。
  • limit −它是可選的。-1 用於預設值,這意味著它是無限的。它設定每個字串中可以執行多少次替換的限制。
  • count −它也像 limit 一樣是可選的。此變數將包含一個數字,指示函式執行後執行了多少次替換。
  • flags −它可以是 preg_offset_capture 和 preg_unmatched_as_null 標誌的組合,這些標誌會影響匹配陣列的格式。
  • 返回值 −preg_replace_callback_array() 返回一個字串或字串陣列。如果發現錯誤,則它將返回空值。如果找到匹配項,則將返回新的主題,否則,將返回未更改的主題。

Preg_replace_callback_array():示例

線上演示

<html>
<head>
<title> PHP 7 Featuretutorialpoint:</title>
</head>
<body>
<?php
   $subject = 'AaaaaaaBbbbCccc';
   preg_replace_callback_array (
      [
         '~[a]+~i' => function ($match) {
            echo strlen($match[0]), ' number of "a" found', PHP_EOL;
         },
         '~[b]+~i' => function ($match) {
            echo strlen($match[0]), ' number of "b" found', PHP_EOL;
         },
         '~[c]+~i' => function ($match) {
            echo strlen($match[0]), ' number of "c" found', PHP_EOL;
         }
      ],
      $subject
   );
?>
</body>
</html>

輸出

上述程式程式碼的輸出為:

7 number of "a" found
4 number of "b" found
5 number of "c" found

更新於: 2021-03-13

232 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.