0

I've created a regular expression in C# but now I'm struggling when trying to run it in PHP. I presumed they'd work the same but obviously not. Does anyone know what needs to be changed below to get it working?

The idea is to make sure that the string is in the format "Firstname Lastname (Company Name)" and then to extract the various parts of the string.

C# code:

string patternName = @"(\w+\s*)(\w+\s+)+";
string patternCompany = @"\((.+\s*)+\)";
string data = "Firstname Lastname (Company Name)";

Match name = Regex.Match(data, patternName);
Match company = Regex.Match(data, patternCompany);

Console.WriteLine(name.ToString());
Console.WriteLine(company.ToString());
Console.ReadLine();

PHP code (not working as expected):

$patternName = "/(\w+\s*)(\w+\s+)+/";
$patternCompany = "/\((.+\s*)+\)/";
$str = "Firstname Lastname (Company Name)";

preg_match($patternName, $str, $nameMatches);
preg_match($patternCompany, $str, $companyMatches);

print_r($nameMatches);
print_r($companyMatches);

3 Answers 3

2

Seems to work here. What you should realize is that when you're capturing matches in a regex, the array PHP produces will contain both the full string that got matched the pattern as a whole, plus each individual capture group.

For your name/company name, you'd need to use

$nameMatches[1] -> Firstname
$nameMatches[2] -> Lastname
and
$companyMatches[1] -> Company Name

which is what got matched by the capture group. the [0] element of both is the entire string.

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

Comments

1

It could be because you're using double-quotes. PHP might be intercepting your escape sequences and removing them since they are not recognized.

1 Comment

From the PHP manual: As in single quoted strings, escaping any other character will result in the backslash being printed too. - although it is a valid point in terms of best practice.
1

Your patterns do appear to extract the information you want. Try replacing the two print_r() lines with:

print "Firstname: " . $nameMatches[1] . "\n";
print "Lastname: " . $nameMatches[2] . "\n";
print "Company Name: " . $companyMatches[1] . "\n";

Is there anything wrong with this output?

Firstname: Firstname 
Lastname: Lastname 
Company Name: Company Name

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.