使用预定义的模板表示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

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
}

Just use explode and substr:

list($first_name, $last_name, $role) = explode(" ", "Jane Joe (Team 1)", 3);
$role = substr($role, 1,-1);

var_dump($first_name, $last_name, $role);

Example: http://ideone.com/Ike0M

Of course this assumes 1 word first and last names.

Try the following:

$str_1 = "Jane Joe (Team 1)";  
preg_match("/^(\w*)\s?(\w*)\s?\\((.*)\\)$/", $str_1, $matches);  
var_dump($matches);  

You could use regex for this (you may have to play with the first two grouping's allowable characters, below allows word characters and hyphens):

$str_1 = "Jane Joe (Team 1)";
$matches = array();
if (preg_match('/([\w-]+) ([\w-]+) \((.*)\)/', $str_1, $matches)) {
    echo $matches[1]; // Jane
    echo $matches[2]; // Joe
    echo $matches[3]; // Team 1
}

Although I would argue that a different approach would be cleaner than passing in a pure string of data, a regular expression would probably achieve this for you.

$strArray = array(
    "Jane Joe (Team 1)",
    "John Joe (Bank)"
);

foreach($strArray as $str) {
    $match = array();
    preg_match("/^\(w*)/", $str, $match);
    $firstName = $match[0];

    preg_match("/\s\(w*)/", $str, $match);
    $lastName = $match[0];

    preg_match("/\((\w)\)/", $str, $match);
    $role = $match[0];
}