[英]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 = '"';
$string = preg_replace($regex,$replace,$string);
這與[start]和[end]之間的文本匹配。 但我想匹配“里面的:
//expected: Hello "world". [start]this is a "mark"[end]. It should work with [start]"several" "marks"[end]
有任何想法嗎?
使用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('"', '"', $m[0]);
},$string);
echo $string;
// => Hello "world". [start]this is a "mark"[end]. It should work with [start]"several" "marks"[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.