I understand how to use PHP’s preg_match() to extract a variable sequence from a string. However, i’m not sure what to do if there are 2 variables that I need to match.
Here’s the code i’m interested in:
$string1 = "help-xyz123@mysite.com";
$pattern1 = '/help-(.*)@mysite.com/';
preg_match($pattern1, $string1, $matches);
print_r($matches[1]); // prints "xyz123"
$string2 = "business-321zyx@mysite.com";
So basically I’m wondering how to extract two patterns: 1) Whether the string’s first part is “help” or “business” and 2) whether the second part is “xyz123” vs. “zyx321”.
The optional bonus question is what would the answer look like written in JS? I’ve never really figured out if regex (i.e., the code including the slashes, /..../) are always the same or not in PHP vs. JS (or any language for that matter).
The solution is pretty simple actually. For each pattern you want to match, place that pattern between parentheses
(...). So to extract any pattern use what’ve you already used(.*). To simply distinguish “help” vs. “business”, you can use|in your regex pattern:The above regex should match both formats.
(help|business)basically says, either matchhelporbusiness.So the final answer is this:
The same regex pattern should be usable in Javascript. You don’t need to tweak it.