tim peterson
tim peterson

Reputation: 24315

Matching multiple variables using regex (PHP/JS)

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 = "[email protected]";
$pattern1 = '/help-(.*)@mysite.com/'; 
preg_match($pattern1, $string1, $matches);
print_r($matches[1]); // prints "xyz123"

$string2 = "[email protected]";

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).

Upvotes: 0

Views: 844

Answers (2)

Fad
Fad

Reputation: 9858

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:

/(help|business)-(.*)@mysite.com/

The above regex should match both formats. (help|business) basically says, either match help or business.

So the final answer is this:

$string1 = "[email protected]";
$pattern1 = '/(help|business)-(.*)@mysite.com/'; 
preg_match($pattern1, $string1, $matches);
print_r($matches[1]); // prints "help"
echo '<br>';
print_r($matches[2]);  // prints "xyz123"

The same regex pattern should be usable in Javascript. You don't need to tweak it.

Upvotes: 1

Simone-Cu
Simone-Cu

Reputation: 1129

Yes, Kemal is right. You can use the same pattern in javascript.

var str="[email protected]";
var patt1=/(help|business)-(.*)@mysite.com/;
document.write(str.match(patt1));

Just pay attention at the return value from the functions that are different. PHP return an array with more information than this code in Javascript.

Upvotes: 1

Related Questions