我使用正則表達式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";
我使用正則表達式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";
// 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 $$$$
?>
好的解決方案。但是,請注意,如果這是您想要的OP,您需要將數組的最終結果轉換爲字符串。 – Neel 2015-05-27 15:05:56
你爲什麼不使用此解決方法:
$vars = explode('@@', str_replace(array('(', ')'), '@@', $text));
它將用@@替換括號,然後將文本分解爲數組。此外,您可以使用array_filter刪除可能的空位。
您可以使用下面的代碼。但請記住,你需要一些額外的檢查,看看是否真的有$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";
?>
我不是在正則表達式中的那麼好,但你可以試試這個.....
$exp=explode("(", $text);
$text1=$exp[0];
$text2=str_replace(array("(",")"), array('',''), $exp[1]);
好主意謝謝,雖然我認爲我寧願使用'trim'而不是'str_replace'你可以使用 – 2013-03-12 11:03:08
.. – 2013-03-12 11:05:39
'([^\)]+)\(([^\)]+)\)'
只需刪除!-chars並添加另一個變量字段(括號區叫什麼名字?)和它的準備:)
http://www.solmetra.com/scripts/regex/index.php是值得知道到g等一些測試很快完成!
這是一個非常詳細的代碼...你可以做短...
<?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;
?>
如果有後應該發生某件事什麼關閉括號? – 2013-03-12 11:06:04