php - Regex to parse all words in a line that follows one of five specific prefixes -


consider

$email = "name: john smith \n           phone: 1-888-555-5555           ..."; 

suppose have code above, , need filter line after word "name: ". have been doing:

if (preg_match("/name:*? (.*)/m", $email, $g) === 1){     echo $g[1]."\n"; //john smith } 

what way write regex statement if string didn't explicitly start word "name: ", 1 of 5 variations of it? here 5 different formats working with:

  • name:
  • full name:
  • f. name:
  • first/last name:
  • name.

this can done several different possible patterns.

this php code demonstrate pattern implementation

$email='name: john smith         phone: 1-888-555-5555         ...';  if(preg_match('/name[:.] \k[^\r\n]*/',$email,$g)){     echo $g[0]; //john smith }  echo "\n\n---\n\n";  $mult='name: john smith         phone: 1-888-555-5555         ...         name. jane smith         phone: 1-888-555-5556         ...         first/last name: joe smith         phone: 1-888-555-5557         ... ';  var_export(preg_match_all('/name[:.] \k[^\r\n]*/',$mult,$g)?$g[0]:'fail'); 

pattern #1: (more lenient) /name[:.] \k[^\r\n]*/ demo

pattern #2: (more literal) ~(?:name.|(?:f(?:. |ull |irst/last ))?name:) \k[^\r\n]*~ demo

some notes:

  • [:.] means match either of characters (colon or dot).
  • \k means "start fullstring match point in pattern".
  • [^\r\n]* means match 0 or more characters not line return or new line characters.
  • the delimiter in pattern #2 changed / ~ slash between irst , last doesn't have escaped.
  • the m flag not necessary.

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - VueJS2 and the Window Object - how to use? -