2

I have a string in PHP.

$str = "1.testone (off) 2.testtwo (off) 3.testthree (off)"; 

I need to split the string between the "." and the " (".

I know I can split the string at either the "." with:

$str1 = explode('.', $str);

This puts the string into an array with the array items being between the ".". Is there any way to make an array with the array items between the "." and " (", and either cut out the rest, or keep it in the array, but explode the string at 2 different spots.

1
  • what is your purpose of splitting 2 different places ? because regular expression can fit better for more complicated pattern. Commented Jun 1, 2013 at 1:45

3 Answers 3

2

Use an explode in an explode, combined with a foreach loop.

$str = "1.testone (off) 2.testtwo (off) 3.testthree (off)"; $explode1 = explode('.', $str); $array = array(); foreach($explode1 as $key => $value) { $explode2 = explode('(', $explode1[$key]); array_push($array, $explode2[0]); } print_r($array); 

Produces:

Array ( [0] => 1 [1] => testone [2] => testtwo [3] => testthree )

Sign up to request clarification or add additional context in comments.

Comments

1
<?php $str = "1.testone (off) 2.testtwo (off) 3.testthree (off)"; $result = preg_split("/\.|\(/", $str); print_r($result); ?> 

result:

Array ( [0] => 1 [1] => testone [2] => off) 2 [3] => testtwo [4] => off) 3 [5] => testthree [6] => off) ) 

Comments

1
$str = "1.testone (off) 2.testtwo (off) 3.testthree (off)"; $arr = array(); foreach(explode('.',$str) as $row){ ($s=strstr($row,'(',true)) && $arr[] = $s; } print_r($arr); //Array ( [0] => testone [1] => testtwo [2] => testthree ) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.