在两个不同的地方分割/爆炸一个PHP字符串

时间:2021-09-14 03:26:25

I have a string in PHP.

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);

str1 =爆炸(美元”。美元,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.

这将字符串放入数组中,数组项位于“。”之间。是否有办法用“.”和“(”之间的数组项来创建一个数组,或者将其余的部分删除,或者将其保存在数组中,但是在两个不同的位置对字符串进行爆炸。

3 个解决方案

#1


2  

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

在爆炸中使用爆炸,结合一个foreach循环。

$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 )

([0] => 1 [1] => testone [2] => test2 [3] => test3)

#2


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)
)

#3


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 )

#1


2  

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

在爆炸中使用爆炸,结合一个foreach循环。

$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 )

([0] => 1 [1] => testone [2] => test2 [3] => test3)

#2


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)
)

#3


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 )