简体   繁体   English

正则表达式删除文本内单引号内的单引号

[英]Regex to remove single quotes inside single quotes inside text

I have some plain text used to generate html, this is the text: 我有一些纯文本用于生成html,这是文本:

lots of stuff

<a  onclick="javascript:do_things('http://somelink.to.something.com', 'string'with'bad'quotes'');">

lots of stuff

The structure of the text is always the same because that text is in turn generated, but the last string used as an argument to the javascript function can change, it may have any number of single quotes or not at all. 文本的结构始终是相同的,因为该文本是依次生成的,但是用作javascript函数参数的最后一个字符串可以更改,它可以有任意数量的单引号或根本没有。 I want to replace those quotes with \\' so that the result is: 我想用\\'替换那些引号,以便结果是:

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\('.*', '(.*)'\)

which gives me this match: 这给了我这个匹配:

string'with'bad'quotes'

But I haven't been able to match the quotes inside, I mean, I could match a quote with .*'.* , but how do I match any number of quotes in any position? 但是我无法匹配内部的引号,我的意思是,我可以匹配带有.*'.*的引号,但是如何在任何位置匹配任意数量的引号?

Thanks 谢谢

How about this? 这个怎么样?

$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);

Output: 输出:

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

We capture the second part of the function then execute a replacement on all single quotes in the found string. 我们捕获函数的第二部分,然后对找到的字符串中的所有单引号执行替换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM