0

I have a textblock which I've exploded into lines, e.g.:

$lines = explode("\n", $textblock);

print_r($lines);

Array
(
    [0] => name surname maybe a middle name (team) something else  
    [1] => (age) something else    
    [2] => etc etc
)

I want to extract name, team and age. To do that I have exploded the strings using brackets as the delimiter but it seems longwinded:

$split_name_team = explode('(', $lines[0]);
$name = $split_name_team[0];
$team = $split_name_team[1];

Then do the same thing basically to get the age:

$split_age = explode('(',$lines[1]);
$age = $split_age[1];

This all works ok, but I feel like I'm repeating a bit already. Is there a faster better way?

willdanceforfun
  • 11,044
  • 31
  • 82
  • 122
  • 2
    Maybe you want to do a simple regex and just grab the values from the input string. – Rizier123 Jun 12 '16 at 17:07
  • 1
    We might help with some regular expressions if you'd provide some more details on your strings (e.g. a sample string). – Jan Jun 12 '16 at 17:08
  • 1
    regular expressions can help you here. When you have clearly defined structure (as you do here), you can just _grab_ needed portions of the string without complicated splitting rituals. This should give you an idea: http://rubular.com/r/zwrzkHOYJA – Sergio Tulentsev Jun 12 '16 at 17:09

1 Answers1

0

you can use regex to do this.

$pattern = "/\(([^)]+)\)/"; //take (....), i.e. take parenthesis and its content
preg_match($pattern, $lines[0], $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches[0]); //return (team) and the position
preg_match($pattern, $lines[1], $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches[0][0]); //return (age) 

Apply the search to your lines and to get only the value uses $matches[0][0]. to get the position use $matches[0]. I suppose that you have only one element in parenthesis and only two elements of the array to look into (otherwise use a for loop)

For a better explanation of regex you can see this explanation. I adapt the code to PHP.

Community
  • 1
  • 1
CiroRa
  • 492
  • 3
  • 13