Last active
March 10, 2022 06:28
-
-
Save AkramiPro/aa843169f510182fd2b312a741473366 to your computer and use it in GitHub Desktop.
PHP Find And Replace Multiple Line Using preg_replace() - Fix line break problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$subject = ' | |
Lorem Ipsum 1 | |
Lorem Ipsum 1.1 | |
Lorem Ipsum 2 | |
Lorem Ipsum 2.1 | |
Lorem Ipsum 2.1.1 | |
Lorem Ipsum 3 | |
Lorem Ipsum 3.1 | |
Lorem Ipsum 4 | |
Lorem Ipsum 4.1 | |
Lorem Ipsum 5 | |
Lorem Ipsum 5.1 | |
'; | |
$find = ' Lorem Ipsum 2 | |
Lorem Ipsum 2.1 | |
Lorem Ipsum 2.1.1'; | |
$replace = 'some new text ... '; | |
// We need replace all new line with \n | |
// @see https://www.npopov.com/2011/12/10/PCRE-and-newlines.html | |
$subject = preg_replace( "/(*BSR_ANYCRLF)\R/", PHP_EOL, $subject ); | |
$find = preg_replace( "/(*BSR_ANYCRLF)\R/", PHP_EOL, $find ); | |
// Convert $find to Regex Pattern | |
// note: 'm' means search in multi line. | |
$pattern = sprintf( '/(%s)/m', preg_quote( $find, '/' ) ); | |
// Replace String | |
$limit = -1; // -1 means replace all, change number if you want to limit the number of replacment. | |
$subject = preg_replace( $pattern, $replace, $subject, $limit, $count ); | |
echo $subject; | |
// @return | |
/* | |
Lorem Ipsum 1 | |
Lorem Ipsum 1.1 | |
some new text ... | |
Lorem Ipsum 3 | |
Lorem Ipsum 3.1 | |
Lorem Ipsum 4 | |
Lorem Ipsum 4.1 | |
Lorem Ipsum 5 | |
Lorem Ipsum 5.1 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment