簡體   English   中英

如何在PHP中通過模式重寫字符串並獲取參數

[英]How to rewrite a string and get params by pattern in php

$string = '/start info@example.com';
$pattern = '/{command} {name}@{domain}';

在php中獲取數組參數,如以下示例所示:

['command' => 'start', 'name' => 'info', 'domain' => 'example.com'] 

$string = '/start info@example.com';
$pattern = '/{command} {email}'; 
['command' => 'start', 'email' => 'info@example.com']

$string = '/start info@example.com';
$pattern = '{command} {email}';
['command' => '/start', 'email' => 'info@example.com']

如果它是單行字符串,則可以使用preg_match和諸如此類的正則表達式

  preg_match('/^\/(?P<command>\w+)\s(?P<name>[^@]+)\@(?P<domain>.+?)$/', '/start info@example.com', $match );

但是根據數據的變化,您可能必須稍微調整一下regx。 這個輸出

  • 命令[1-6] start
  • 名稱[7-11] info
  • 域[12-23] example.com

但它也會在數組中包含數字索引。

https://regex101.com/r/jN8gP7/1

只是用英語來分解一下。

前導^是行的開頭,然后命名為capture( \\w (任何az AZ 0-9 _)),然后是一個空格\\s然后命名為capture of(除@t符號[^@] ),然后是@t在@簽名,然后捕獲的名稱(任何.+?$結尾)

這將捕獲此格式的任何內容,

(abc123_)空間(@除外)@(任何東西)

暫無
暫無

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

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