[英]PHP split string into 2 variables from containing brackets
我正在使用正則表達式,雖然這只提取括號內的文本,我想完全刪除它:
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 $$$$
?>
$data = preg_split("/[()]+/", $text, -1, PREG_SPLIT_NO_EMPTY);
您可以使用以下代碼。 但請記住,你確實需要一些額外的檢查來確定是否真的有$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]);
'([^\)]+)\(([^\)]+)\)'
只需刪除!-chars並添加另一個變量字段(括號區域的名稱?)並准備好:)
http://www.solmetra.com/scripts/regex/index.php值得知道快速完成一些測試!
這是一個非常詳細的代碼......你可以做得更短......
<?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;
?>
為什么不使用此解決方法:
$vars = explode('@@', str_replace(array('(', ')'), '@@', $text));
它將用@@替換括號,然后將文本分解為數組。 此外,您可以使用array_filter刪除可能的空位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.