我已经考虑这个问题几个小时了,虽然我有点新手,但我相信我有一种方法可以提取提及和警报并将它们存储到两个一维数组中。
<?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/>';
}
?>
我使用的正则表达式的解释(由 Regex Buddy 提供):@(\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 “|,!?” «|,|!|?»
这甚至会返回被括号偏移的消息中的单词(例如(hello))。您应该能够使用数组中定义的变量执行您描述的任何操作。如果这不正确,或者您无法做到,请告诉我,我会看看我能想出什么。