我一直在想這個問題幾個小時,雖然我有點新手,但我相信我有一種方法可以提取提及和警報並將它們存儲到兩個一維數組中。
<?php
//a variable ($string) that I thought might look like what you are describing
$string='@steve how are you? @tom nice to hear from you. So happy that you joined @joe, cool! @mike sweeet!';
//regex to pull out the mentions and the messages
preg_match_all('/@(\w+)|\s+([(\w+)\s|.|,|!|?]+)/', $string, $result, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($result[0]); $i++) {
$mention[$i]= $result[1][$i];
$message[$i]= $result[2][$i];
}
//test to make sure that all mentions are stored
for ($j = 0; $j< $i; $j++){
echo $mention[$j],'<br/>';
}
//test to make sure that all messages are stored
for ($k = 0; $k< $j; $k++){
echo $message[$k],'<br/>';
}
?>
的解釋,如正則表達式好友提供的),我使用了正則表達式:@(\ w +)| \ S +([。!?(\ w +)\ s | |,| |] + ):
Match either the regular expression below (attempting the next alternative only if this one fails) «@(\w+)»
Match the character 「@」 literally «@»
Match the regular expression below and capture its match into backreference number 1 «(\w+)»
Match a single character that is a 「word character」 (letters, digits, and underscores) «\w+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Or match regular expression number 2 below (the entire match attempt fails if this one fails to match) «\s([(\w+)\s|\.|,|!|?]+)»
Match a single character that is a 「whitespace character」 (spaces, tabs, and line breaks) «\s+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the regular expression below and capture its match into backreference number 2 «([(\w+)\s|\.|,|!|?]+)»
Match a single character present in the list below «[(\w+)\s|\.|,|!|?]+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
The character 「(」 «(»
A word character (letters, digits, and underscores) «\w»
One of the characters 「+)」 «+)»
A whitespace character (spaces, tabs, and line breaks) «\s»
The character 「|」 «|»
A . character «\.»
One of the characters 「|,!?」 «|,|!|?»
這甚至會返回由圓括號(例如(你好))偏移的消息中的單詞。您應該能夠使用數組中定義的變量來執行您描述的任何操作。如果這是不正確的,或者你不能,讓我知道,我會看到我能想出什麼。
由於正則表達式是完美的,作爲通知,我想保留它我的提醒方式,我只需要知道如何提取提及時,我張貼表單,並將他們每個插入警報表,謝謝。 – Engine
給你一些筆記。在保存評論之前,用戶可以用他們的ID替換用戶名,例如。它防止在用戶更改其用戶名時無法連接到用戶配置文件。 然後,你可以簡單地提取用戶id在提及,並用這個正則表達式preg_match_all('/ /',$ comment,$ users)將它們替換爲他們的用戶名。 –
honzahommer