简体   繁体   中英

Wrap single quotes and replace line break by regex

I have the strings as below

Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School

I want to change it by regex as below:

'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 

I have tried replace(/^(.*)$/, '$&',) then replace(/\\r\\n/, '') and it works. But I don't want to do the replace two time, so I combine this syntax to replace(/^(.*)$\\r\\n/, '$&',) . Could someone please advise why my syntax is not work?

Thank you.

Live demo http://regexr.com?37nk7

For a regex, you should be able to use this:

replace(/^(.*)$[\r\n]*/g, "'$1', ")

The [\\r\\n]* is simply to account for different EOL scenarios, just in case. Then the $1 serves as the back-reference for a single group, and the trailing g at the end of the regexp object is the "global" flag for performing the replacement globally.

Updated demo: http://regexr.com?37nkd

implode("', '", explode("\n", $longString))

Edit #1: Ooops, forget the JS not PHP.

var longStringArray = longString.split("\n");
var newLongString = longStringArray.join("', '");

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