Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 23rd, 2012  |  syntax: None  |  size: 2.13 KB  |  hits: 11  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How do I get data a regular expression does't match?
  2. $tweet = '#notes @username !high_priority [Project Name] Tweet content';
  3.        
  4. $match = preg_match_all('/(#\w*[a-zA-Z_]+\w*)|(!\w*[a-zA-Z_]+\w*)|(@\w*[a-zA-Z_]+\w*)|(\[[^\]]*\])/i',
  5.     $tweet,
  6.     $matches);
  7.        
  8. $tweet = '@username Tweet content [Project Name] #notes !high_priority';
  9.        
  10. $data = array(
  11.     'hash' => '',
  12.     'user' => '',
  13.     'priority' => '',
  14.     'project' => '',
  15.     'content' => ''
  16. );
  17.  
  18. $parsingProjectName = false;
  19. foreach(explode(' ', $tweet) as $piece)
  20. {
  21.     switch(substr($piece, 0, 1))
  22.     {
  23.         case '#':
  24.             $data['hash'] = substr($piece, 1);
  25.             break;
  26.         case '@':
  27.             $data['user'] = substr($piece, 1);
  28.             break;
  29.         case '!':
  30.             $data['priority'] = substr($piece, 1);
  31.             break;
  32.         case '[':
  33.             // Check if the project name is longer than 1 word
  34.             if(strpos($piece, -1) == ']')
  35.             {
  36.                 $data['project'] = substr($piece, 1, -1);
  37.             }
  38.             else
  39.             {
  40.                 // There will be more to parse in the next piece(s)
  41.                 $parsingProjectName = true;
  42.                 $data['project'] = substr($piece, 1) . ' ';
  43.             }
  44.             break;
  45.         default:
  46.             if($parsingProjectName)
  47.             {
  48.                 // Are we at the end yet?
  49.                 if(strpos($piece, -1) == ']')
  50.                 {
  51.                     // Yes we are
  52.                     $data['project'] .= substr($piece, 1, -1);
  53.                     $parsingProjectName = false;
  54.                 }
  55.                 else
  56.                 {
  57.                     // Nope, there is more
  58.                     $data['project'] .= substr($piece, 1) . ' ';
  59.                 }
  60.             }
  61.             else
  62.             {
  63.                 // We aren't in the middle of parsing the project name, and this piece doesn't start with one of the special chars, so assume it is content
  64.                 $data['content'] .= $piece . ' ';
  65.             }
  66.     }
  67. }
  68.  
  69. // There will be an extra space on the end; remove it
  70. $data['content'] = substr($data['content'], 0, -1);
  71.        
  72. ...\s*[\w_]+\s*...