简体   繁体   中英

PHP Regex Replace Two Slashes (//) to New Line

What I'm trying to do here is take a string that might have what would normally be a code comment, and replace that with something else, especially wrapping it in something else. I'm pretty sure the preg_replace function would work here, but I don't have an idea on where to start with the Regex. For example:

Hello world //this is a comment
Testing //not testing
Test again

Would turn into

Hello world %//this is a comment%
Testing %//not testing%
Test again

preg_replace('???', '%$1%', $matches); is as much as I can figure out on my own, any help is much appreciated!

preg_replace('~//.*$~m', '', $str);

This will remove everything after (and including) // to the end of the line

http://ideone.com/Xhmpd

preg_replace('~//.*$~m', 'foo \\0 bar', $str);

This will wrap them with foo bar around

http://ideone.com/IqkWM

Try this:

$string = "Hello world //this is a comment";
preg_replace('/\/\/.*/', '%$0%', $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