我正在開發一個簡單的提及系統和我的 PHP 腳本,我需要client:6從較大的文本中提取一個或多個類似 @mention 的文本@[John Doe (#6)](client:6)。
前任。 This is my text how do you like it @John and do you have any thoughts @Jane
在 php 中,字串看起來像。
This is my text how do you like it @[John Doe (#6)](client:6) and do you have any thoughts @[Jane Doe (#7)](client:7)
我需要得到一個陣列 array('client:6','client:7')
uj5u.com熱心網友回復:
許多可能的方法之一是
@\[[^][] \]\s*\(\K[^()]
在 regex101.com 上查看演示。
就正則運算式而言,這歸結為
@ # "@" literally
\[ # "[" literally
[^][] # not "[" nor "]" as many times as possible
\]\s* # followed by "]" literally whitespaces, eventually
\( # you name it - "(" literally
\K # forget all what has been matched that far
[^()] # not "(" nor ")"
在PHP這可能是
<?php
$data = "This is my text how do you like it @[John Doe (#6)](client:6) and do you have any thoughts @[Jane Doe (#7)](client:7)";
$regex = "~@\[[^][] \]\s*\(\K[^()] ~";
preg_match_all($regex, $data, $matches);
print_r($matches);
?>
并且會產生
Array
(
[0] => Array
(
[0] => client:6
[1] => client:7
)
)
在 ideone.com 上查看演示。
uj5u.com熱心網友回復:
\w :\d 應該管用。
在句子中:
這是我的文字,你喜歡它嗎@John Doe(#6),你有什么想法@Jane Doe(#7)
它應該找到 client:6 和 client:7 。
例如,您可以使用https://regexr.com/實時試用您的正則運算式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/361178.html
下一篇:忽略在重復組中捕獲的領先空間?
