簡體   English   中英

用正則表達式獲取標記內的引號

[英]get quotation marks inside tag with regex

在那里。 我試圖在特定的起始字符串中獲取所有引號。 假設我有這個字符串:

`Hello "world". [start]this is a "mark"[end]. It should work with [start]"several" "marks"[end]`

現在,我想每一個“里面的[開始]。[結束]被替換為"

$string = 'Hello "world". [start]this is a "mark"[end]. It should work with [start]"several" "marks"[end]';
$regex = '/(?<=\[start])(.*?)(?=\[end])/';
$replace = '&quot;';

$string = preg_replace($regex,$replace,$string);

這與[start]和[end]之間的文本匹配。 但我想匹配“里面的:

//expected: Hello "world". [start]this is a &quot;mark&quot;[end]. It should work with [start]&quot;several&quot; &quot;marks&quot;[end]

有任何想法嗎?

(?s)"(?=((?!\[start\]).)*\[end\])

現場演示

說明:

 (?s)                       DOT_ALL modifier
 "                          Literal "
 (?=                        Begin lookahead
      (                         # (1 start)
           (?! \[start\] )          Current position should not be followed by [start]
           .                        If yes then match
      )*                        # (1 end)
      \[end\]                   Until reaching [end]
 )                          End lookahead

PHP現場演示

使用preg_replace_callback的方法允許使用更簡單的正則表達式(考慮到您的字符串始終具有成對的非嵌套[start]...[end]對):

$string = 'Hello "world". [start]this is a "mark"[end]. It should work with [start]"several" "marks"[end]';
$regex = '/\[start].*?\[end]/s';
$string = preg_replace_callback($regex, function($m) {
    return str_replace('"', '&quot;', $m[0]);
},$string);
echo $string;
// => Hello "world". [start]this is a &quot;mark&quot;[end]. It should work with [start]&quot;several&quot; &quot;marks&quot;[end]

請參閱PHP IDEONE演示

'/\\[start].*?\\[end]/s'正則表達式匹配[start] ,然后匹配任何0+字符(包括使用/s DOTALL修飾符后的換行符,然后是[end]

如果你需要確保第一個[start][end]之間的最短窗口,你需要使用一個帶有馴化貪婪令牌的正則表達式,如Revo的答案: '/\\[start](?:(?!\\[(?:start|end)]).)*\\[end]/s' (參見PHP演示正則表達式演示 )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM