php - How to preg_match first occurrence in a string -


i trying extract from:address email body. here have far:

$string = "from: user1@somewhere.com test.. original message sent from: user2@abc.com";  $regexp = "/(from:)(.*)/"; $outputarray = array(); if ( preg_match($regexp, $string, $outputarray) ) { print "$outputarray[2]"; } 

i email address of first occurrence of from: .. suggestions?

your regex greedy: .* matches any 0 or more characters other newline, many possible. also, there no point in using capturing groups around literal values, creates unnecessary overhead.

use following regular expression:

^from:\s*(\s+) 

the ^ makes sure start searching beginning of string,from: matches sequence of characters literally, \s* matches optional spaces, (\s+) captures 1 or more non-whitespace symbols.

see sample code:

<?php $string = "from: user1@somewhere.com test.. original message sent from: user2@abc.com";  $regexp = "/^from:\s*(\s+)/"; $outputarray = array(); if ( preg_match($regexp, $string, $outputarray) ) { print_r($outputarray[1]); } 

the value looking inside $outputarray[1].


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -