2013-03-12 86 views
2

我使用正則表達式from雖然這僅提取括號內的文字,我想徹底刪除:PHP字符串分割到2個變量從包含括號

if(preg_match('!\(([^\)]+)\)!', $text, $match)) 
    $text = $match[1]; 

如我有:my long text string (with another string)

我如何獲得:

$var1 = "my long text string"; 
$var2 = "with another string"; 
+1

如果有後應該發生某件事什麼關閉括號? – 2013-03-12 11:06:04

回答

10
// This is all you need 
<?php $data = explode('(' , rtrim($str, ')')); ?> 

例子:

<?php 
$str = 'your long text string (with another string)'; 
$data = explode('(' , rtrim($str, ')'));  

print_r($data); 


// output 

// Array 
// (
//  [0] => my long text string 
//  [1] => with another string 
//) 
// profit $$$$ 

?> 
+0

好的解決方案。但是,請注意,如果這是您想要的OP,您需要將數組的最終結果轉換爲字符串。 – Neel 2015-05-27 15:05:56

0

你爲什麼不使用此解決方法:

$vars = explode('@@', str_replace(array('(', ')'), '@@', $text)); 

它將用@@替換括號,然後將文本分解爲數組。此外,您可以使用array_filter刪除可能的空位。

1

您可以使用下面的代碼。但請記住,你需要一些額外的檢查,看看是否真的有$out[0][0]$out[0][1]

<?php 
    $string = "my long text string (with another string)"; 
    preg_match_all("/(.*)\((.*)\)/", $string, $out, PREG_SET_ORDER); 
    print_r($out); 
    /* 
    Array 
    (
      [0] => Array 
        (
          [0] => my long text string (with another string) 
          [1] => my long text string 
          [2] => with another string 
        ) 

    ) 
    */ 

    $var1 = $out[0][1]; 
    $var2 = $out[0][2]; 
    //$var1 = "my long text string"; 
    //$var2 = "with another string"; 
    ?> 
1

我不是在正則表達式中的那麼好,但你可以試試這個.....

$exp=explode("(", $text); 
$text1=$exp[0]; 
$text2=str_replace(array("(",")"), array('',''), $exp[1]); 
+0

好主意謝謝,雖然我認爲我寧願使用'trim'而不是'str_replace'你可以使用 – 2013-03-12 11:03:08

+0

.. – 2013-03-12 11:05:39

4
$data = preg_split("/[()]+/", $text, -1, PREG_SPLIT_NO_EMPTY); 
+0

我相信你不得不逃避'('和')'s,但是。 – h2ooooooo 2013-03-12 11:08:45

+0

不在[]內部,因爲在[]中,所有特殊字符都是正常的:p。看看:http://sandbox.onlinephpfunctions.com/code/2249ca5e439760eec25161a6b14b2cdbfd18ecc3 – MatRt 2013-03-12 11:09:43

1

這是一個非常詳細的代碼...你可以做短...

<?php 
$longtext = "my long text string (with another string)"; 
$firstParantheses = strpos($longtext,"("); 

$firstText = substr($longtext,0,$firstParantheses); 

$secondText = substr($longtext,$firstParantheses); 

$secondTextWithoutParantheses = str_replace("(","",$secondText); 
$secondTextWithoutParantheses = str_replace(")","",$secondTextWithoutParantheses); 

$finalFirstPart = $firstText; 
$finalSecondPart = $secondTextWithoutParantheses; 

echo $finalFirstPart." ------- ".$finalSecondPart; 
?> 
相關問題