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++;
}
我想要做的,是打印原來的$的人,但與$ firstName和$ lastName是相反的。我可以替換這些值,然後打印出每個變量,但是除非我爲每一行格式化,否則它不會具有與$原本相同的格式。我想知道是否有辦法做到這一點,而不是格式化每個輸出看起來與原來的$ person變量相同。
謝謝!
謝謝你,這工作。你介意解釋你在那裏寫的正則表達式嗎?還有2美元,1美元?再次感謝。 – stytown 2012-04-27 04:32:06
在正則表達式中,括號定義了稍後可以使用美元符號引用的組。在這種情況下,最左邊的圓括號組是匹配的名字,第二組匹配姓氏。 \ s匹配任何空格字符,並且加號表示即使重複也會繼續匹配它。正斜槓\:意味着從字面上匹配一個冒號,因爲冒號在preg中可能有意義。最後,'$ 2,$ 1:'是先輸出我們的匹配姓氏;後跟一個逗號和名字 - 然後替換我們匹配的冒號。我希望這有助於! – philwinkle 2012-04-27 04:36:17
正反斜槓並不容易在堆棧上標記爲帶反碼的代碼! – philwinkle 2012-04-27 04:37:41