douchen9569 2012-04-27 04:08
浏览 23
已采纳

使用RegEx交换两个变量

So here is my code, and then I will explain what I am having trouble with:

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++;
}

What I want to do, is print the original $person, but with the $firstName and $lastName 's reversed. I'm able to replace the values and then print out each variable, but then it wouldn't have the same format as $person originally did unless I formatted each line. I was wondering if there was a way to do it without formatting each output to look identical to the original $person variable.

Thanks!

  • 写回答

1条回答 默认 最新

  • drqefnd544707688 2012-04-27 04:28
    关注

    It looks as if Firstname and Lastname are always separated by whitespace and preceed the first colon character... if this is correct the above may be overkill. Try this:

    echo $newPerson = (preg_replace("/(.*?)\s+(.*?)\:/", '$2,$1:', $person))."<br/>";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度