0

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

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 变量相同的情况下做到这一点。

谢谢!

4

1 回答 1

0

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

echo $newPerson = (preg_replace("/(.*?)\s+(.*?)\:/", '$2,$1:', $person))."<br/>";
于 2012-04-27T04:28:25.903 回答