用正则表达式交换两个变量


Swapping two variables with RegEx

这是我的代码,然后我将解释我遇到的问题:

foreach($people as $person){
    // counter for each person
    $counter = 0;
    // get variables for each item
    list($fullName,$phoneNumber,$address,$birthday,$salary) = explode(':', $person);
    // get variables for first and last name
    list($firstName, $lastName) = explode(" ", $fullName);
    // get variables for phone numbers
    list($areaCode, $middleDigits, $lastDigits) = explode('-',$phoneNumber);
    //get variables for address
    list($street,$city,$statezip) = explode(", ", $address);
    // get variables for state and zip separately
    list($state,$zipCode) = explode(" ", $statezip);

    // print file with the first and last names reversed
    $tempFName = $firstName;
    $tempLName = $lastName;
    echo $newPerson = (preg_replace("/($tempLName)($tempFName)/", $firstName, $lastName, $person))."<br/>";
    $counter++;
}

我想做的是打印原始$person,但$firstName和$lastName颠倒了。 我可以替换值,然后打印出每个变量,但是除非我格式化每一行,否则它的格式不会与$person原来的格式相同。 我想知道是否有一种方法可以在不格式化每个输出以使其看起来与原始$person变量相同的情况下做到这一点。

谢谢!

看起来名字和姓氏总是用空格分隔,并且在第一个冒号字符之前......如果这是正确的,上述内容可能是矫枉过正。试试这个:

echo $newPerson = (preg_replace("/(.*?)'s+(.*?)':/", '$2,$1:', $person))."<br/>";