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