Regex用于删除文本内的单引号


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

I got this far:

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 Demo: https://regex101.com/r/rM5mM3/3

我们捕获函数的第二部分,然后对找到的字符串中的所有单引号执行替换。