How can regression in a recursive regular expression be combined?

I have a line like this:

$data = 'id=1 username=foobar comment=This is a sample comment'; 

And I would like to remove \n in the third field ( comment=... ).

I have this regex that serves my purpose, but not so well:

 preg_replace('/\bcomment=((.+)\n*)*$/', "comment=$2 ", $data); 

My problem is that every match in the second group overwrites the previous match. So instead:

 '... comment=This is a sample comment' 

I ended up with this:

 '... comment= comment' 

Is there a way to store intermediate backlinks in a regular expression? Or do I need to map each occurrence within a loop?

Thanks!

+4
source share
1 answer

It:

 <?php $data = 'id=1 username=foobar comment=This is a sample comment'; // If you are at PHP >= 5.3.0 (using preg_replace_callback) $result = preg_replace_callback( '/\b(comment=)(.+)$/ms', function (array $matches) { return $matches[1] . preg_replace("/[\r\n]+/", " ", $matches[2]); }, $data ); // If you are at PHP < 5.3.0 (using preg_replace with e modifier) $result = preg_replace( '/\b(comment=)(.+)$/mse', '"\1" . preg_replace("/[\r\n]+/", " ", "\2")', $data ); var_dump($result); 

will give

 string(59) "id=1 username=foobar comment=This is a sample comment" 
+4
source

Source: https://habr.com/ru/post/1346036/


All Articles