[英]Regex to remove single quotes inside single quotes inside text
我有一些純文本用於生成html,這是文本:
lots of stuff
<a onclick="javascript:do_things('http://somelink.to.something.com', 'string'with'bad'quotes'');">
lots of stuff
文本的結構始終是相同的,因為該文本是依次生成的,但是用作javascript函數參數的最后一個字符串可以更改,它可以有任意數量的單引號或根本沒有。 我想用\\'替換那些引號,以便結果是:
lots of stuff
<a onclick="javascript:do_things('http://somelink.to.something.com', 'string\'with\'bad\'quotes\'');">
lots of stuff
我已經走了這么遠:
onclick="javascript:do_things\('.*', '(.*)'\)
這給了我這個匹配:
string'with'bad'quotes'
但是我無法匹配內部的引號,我的意思是,我可以匹配帶有.*'.*
的引號,但是如何在任何位置匹配任意數量的引號?
謝謝
這個怎么樣?
$string = 'lots of stuff
<a onclick="javascript:do_things(\'http://somelink.to.something.com\', \'string\'with\'bad\'quotes\'\');">
lots of stuff';
echo preg_replace_callback('~(<a\h*onclick="javascript:do_things\(\'.*?\',\h*\')(.*)(\'\);">)~', function($match){
return $match[1] . str_replace("'", "\'", $match[2]) . $match[3];}, $string);
輸出:
lots of stuff
<a onclick="javascript:do_things('http://somelink.to.something.com', 'string\'with\'bad\'quotes\'');">
lots of stuff
Regex101演示: https ://regex101.com/r/rM5mM3/3
我們捕獲函數的第二部分,然后對找到的字符串中的所有單引號執行替換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.