简体   繁体   中英

PHP Regular extract parts from a string

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM