0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.