[英]Doubt on Regular expressions in PHP
朋友们,
我有一个愚蠢的怀疑:
假设我有这样一条线
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
如何实现这一目标?
如果你只想删除尾随的逗号,你可以只使用substr ...
$newstr = substr($str, 0, strlen($str)-1);
这样的东西......
编辑:>好的,试着再次回答这个问题......这会有用吗?
$new_heading = preg_replace("/\([^\)]+\)/",",",$new_heading);
$newstr = substr($new_heading, 0, strlen($str)-1);
编辑:>回复您的评论如下。 谢谢:)我没有真正使用一本书,只是RegxLib
(更新)试试这个,
$text = "Heading: Text1 (a, b) Text2. (d, f) Text3 (g, 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";
如果你看一下preg_replace()的定义,就会有一个名为$limit
的参数。 以下是解决问题的步骤:
码:
preg_match_all("/\([^\)]+\)/",$new_heading,$matches);
$new_heading = preg_replace("/\([^\)]+\)/",",",$new_heading, count($matches) - 1);
$new_heading = preg_replace("/\([^\)]+\)/","",$new_heading);
替代方案:
$count
的值,这是第五个参数。 码:
preg_replace("/\([^\)]+\)/","",$new_heading, null, $count);
$new_heading = preg_replace("/\([^\)]+\)/",",",$new_heading, $count - 1);
$new_heading = preg_replace("/\([^\)]+\)/","",$new_heading);
你能用两个表达吗?
$text = "Heading: Text1 (a, b) Text2. (d, f) Text3 (g, h)";
$new = preg_replace("/\([^)]*\)(?=.*?\([^)]*\))/",",",$text);
$new = preg_replace("/\([^)]*\)/","",$new);
echo $new . "\n";
第一个用逗号替换所有实例但是最后一个。 最后一个例子(g, h)
仍然存在。 然后第二个表达式用空字符串替换所有剩余的实例(只有一个)。
<?php
$line = 'Heading: Text1 (a, b) Text2. (d, f) Text3 (g, h)';
$line = substr(preg_replace('/\([^\)]+\)/', ',', $line), 0, -1);
?>
或者你可以使用两个正则表达式:
<?php
$line = 'Heading: Text1 (a, b) Text2. (d, f) Text3 (g, h)';
$line = preg_replace('/ \([^\)]+\)$/', '', $line);
$line = preg_replace('/\([^\)]+\)/', ',', $line);
?>
但这太过分了。 使用一个正则表达式来简化。
这可能看起来效率低下但会解决您的问题。 策略是
preg_match
来查找模式的出现次数,在这种情况下是括号并说出它的n
preg_replace
通过逗号将limit
参数设置为n-1
来替换n-1
括号的出现次数 preg_replace
用空字符串替换括号集 使用这样的代码:
$str = 'Text1 (a, b) Text2. (d, f) Text3 (g, h)';
$arr = preg_split('~\([^)]*\)~', $str, -1 , PREG_SPLIT_NO_EMPTY);
var_dump(implode(',', $arr));
string(23) "Text1 , Text2. , Text3 "
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.