问题描述
|
朋友们
我有一个愚蠢的疑问:
假设我有这样一条线
heading: Value1; SomeText1 (a,b,c),Value 2; SomeText2 (d,e,f)
我想删除所有分号并删除方括号(包括方括号)中的所有内容。我设法用这段代码做到了
if (strstr($line,\'heading\')){
$new_heading = str_replace(\";\",\"\",$line); // Replaces semi-colon
$new_heading = preg_replace(\"/\\([^\\)]+\\)/\",$new_heading); //Removes Text With in Brackets
$line = $new_heading;
echo $line; //Outputs \"heading: Value1 SomeText1,Value 2 SomeText2\"
}
现在假设我有这样一条线
heading: Text1 (a,b) Text2. (d,f) Text3 (g,h)
我要实现的是...删除括号中的所有内容(包括括号),然后用逗号替换。但是,括号的最后一次出现不应该用逗号代替。
我的意思是输出应该是
heading: Text1,Text2.,Text3
如何做到这一点?
解决方法
可以使用两个表达式吗?
$text = \"Heading: Text1 (a,b) Text2. (d,f) Text3 (g,h)\";
$new = preg_replace(\"/\\([^)]*\\)(?=.*?\\([^)]*\\))/\",\",$text);
$new = preg_replace(\"/\\([^)]*\\)/\",\"\",$new);
echo $new . \"\\n\";
第一个替换所有实例,但最后一个替换为逗号。最后的实例“ 5”仍然存在。然后,第二个表达式用一个空字符串替换所有剩余的实例(只有一个)。
, 如果查看preg_replace()的定义,则有一个名为$limit
的参数。因此,以下是解决您的问题的步骤:
使用preg_match_all来计算括号
在preg_replace中使用该数字-1并将方括号替换为逗号
再次使用preg_replace将最后一个括号替换为空字符串
码:
preg_match_all(\"/\\([^\\)]+\\)/\",$new_heading,$matches);
$new_heading = preg_replace(\"/\\([^\\)]+\\)/\",count($matches) - 1);
$new_heading = preg_replace(\"/\\([^\\)]+\\)/\",$new_heading);
选择:
像以前一样使用preg_replace,但不要存储结果。仅使用第五个参数$count
的值。
在preg_replace中使用该数字-1并将方括号替换为逗号
再次使用preg_replace将最后一个括号替换为空字符串
码:
preg_replace(\"/\\([^\\)]+\\)/\",null,$count);
$new_heading = preg_replace(\"/\\([^\\)]+\\)/\",$count - 1);
$new_heading = preg_replace(\"/\\([^\\)]+\\)/\",$new_heading);
, (更新)尝试一下,
$text = \"Heading: Text1 (a,h)\";
preg_match_all(\"/\\([^\\)]+\\)/\",$text,$brackets);
$bracket_c = count($brackets);
for($bracket_i = 0; $bracket_i < $bracket_c; $bracket_i += 1){
if($bracket_i == $bracket_c - 1){
$text = str_replace($brackets[$bracket_i],$text);
}else{
$text = str_replace($brackets[$bracket_i],$text);
}
}
echo $text . \"\\n\";
, 如果您只想删除结尾的逗号,则可以使用substr ...
$newstr = substr($str,strlen($str)-1);
像这样
编辑:>好的,尝试再次回答这个问题。
$new_heading = preg_replace(\"/\\([^\\)]+\\)/\",$new_heading);
$newstr = substr($new_heading,strlen($str)-1);
编辑:>为回应您在下面的评论。谢谢:)我并没有真正用过书,只是RegxLib
, <?php
$line = \'Heading: Text1 (a,h)\';
$line = substr(preg_replace(\'/\\([^\\)]+\\)/\',\',$line),-1);
?>
或者使用两个正则表达式,您可以执行以下操作:
<?php
$line = \'Heading: Text1 (a,h)\';
$line = preg_replace(\'/ \\([^\\)]+\\)$/\',\'\',$line);
$line = preg_replace(\'/\\([^\\)]+\\)/\',$line);
?>
但这太过分了。为了简单起见,请使用一个正则表达式。
, 这看起来效率低下,但可以解决您的问题。该策略是
用preg_match
找出数字
模式的出现,在这种情况下,将其括起来并说出
n
用preg_replace
代替
逗号出现“ 18”括号的情况
将limit
参数设置为n-1
用preg_replace
替换套装
用空字符串括起来
, 使用如下代码:
$str = \'Text1 (a,h)\';
$arr = preg_split(\'~\\([^)]*\\)~\',$str,-1,PREG_SPLIT_NO_EMPTY);
var_dump(implode(\',$arr));
输出值
string(23) \"Text1,Text2.,Text3 \"