简体   繁体   中英

Regex to remove single quotes inside single quotes inside text

I have some plain text used to generate html, this is the text:

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. 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

We capture the second part of the function then execute a replacement on all single quotes in the found string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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