[英]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.