duanfuxing2212 2012-02-20 20:55
浏览 31
已采纳

使用预定义的模板表示php字符串

I need to phrase php strings and "explode" it into 3 variables based on a template.

I tried doing it using the explode function, however it's a little messy.

    list($name, $role) = explode(' (', $value);
    list($firstName, $lastName) = explode(' ', $name);

For example, I have these strings:

$str_1 = "Jane Joe (Team 1)";
$str_2 = "John Joe (Bank)";

I need to extract first_name, last_name and the role, which is the string in the parentheses.

I also tried regular expressions, but I'm a little rusty with regular expressions

  • 写回答

5条回答 默认 最新

  • duanmianxue2687 2012-02-20 21:01
    关注

    You can try using Regular Expression to get that parts of input string:

    PHP preg_match function: http://php.net/manual/en/function.preg-match.php

    preg_match('~^(.+) (.+)\((.+\))$~', $str_1, $matches);
    

    That kind of call makes that the @matches array contain:

    • $matches[0] : whole input string
    • $matches[1] : first name
    • $matches[2] : last name
    • $matches[3] : role

    You also can check if that pattern match input string:

    if(preg_match('^(.+) (.+)\((.+\))$', $str_1, $matches)) {
        // do something with matches here
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示