开发者

preg_replace a specific pattern

开发者 https://www.devze.com 2023-01-11 07:25 出处:网络
I would like to us开发者_如何学编程e preg_replace to replace \"* @license until */\" with \"testing\".

I would like to us开发者_如何学编程e preg_replace to replace "* @license until */" with "testing".

How can I do it?

My text is the one below:

/*
 * @copyright  
 * @license  
 *
 */

I hope everyone have understand my question correctly.


Here is one regex that does what you want (run it in multi-line mode)

^\s*\*\s*@license(?:(?!\s*\*/)[\s\S])+

It matches the part that is striked:

/*
 * @copyright  
 * @license  
 *
 */

Explanation:

^              ~ start-of-string
\s*            ~ any number of white space
\*             ~ a literal star
\s*            ~ any number of white space
@license       ~ the string "@license"
(?:            ~ non-capturing group
  (?!          ~   negative look ahead (a position not followed by...):
    \s*        ~     any number of white space
    \*         ~     a literal star
    /          ~     a slash
  )            ~   end lookahead (this makes it stop before the end-of-comment)
  [\s\S]       ~   match any single character
)+             ~ end group, repeat as often as possible

Note that the regex must still be escaped according to PHP string rules and according to preg_replace() rules.

EDIT: If you feel like it - to make absolutely sure that there really is an end-of-comment marker following the matched text, the regex can be expanded like this:

^\s*\*\s*@license(?:(?!\s*\*/)[\s\S])+(?=\s*\*/)
                                      ↑           positve look ahead for 
                                      +-----------an end-of-comment marker


Well, it's not too hard. All you need to do is use the s modifier (PCRE_DOT_ALL, which makes a . in the regex match new lines):

$regex = '#\\*\\s*@license.*?\\*/'#s';
$string = preg_replace($regex, '*/', $string);

That should work for you (note, untested)...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号