我正在使用正则表达式,虽然这只会提取括号内的文本,但我想完全删除它:
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 删除可能的空位置。