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/>";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c