preg_replace Text Between Two Strings

If you need to change text between two strings, you can read this article.

You can select the text between strings and modify it easily. You need preg_replace() for doing this action.

Example 1: Remove text between two strings with delimiter
[php]
$source = "One Two Three Four Five Six";
$source = preg_replace(‘/Two(.*)Four/’,"", $source);
echo $source; // One Five Six
[/php]

Example 2: Remove text between two strings without delimiter
[php]
$source = "One Two Three Four Five Six";
$source = preg_replace(‘/(Two)(.*)(Four)/’,"$1 $3", $source);
echo $source; // One Two Four Five Six
[/php]

Example 3: Modify text between two strings
[php]
$source = "One Two Three Four Five Six";
$source = preg_replace(‘/(Two)(.*)(Four)/’,"$1 3 $3", $source);
echo $source; // One Two 3 Four Five Six
[/php]

These example do not have newline. newlines are excluded. If your example includes newlines, you have to add “s” pattern modifier.

Example 4: Remove text between two strings without delimiter (newlines)

[php]
$source = "
One
Two
Three
Four
Five
Six
";

$source = preg_replace(‘/(Two)(.*)(Four)/s’,"$1 $3", $source);
echo $source; // One Two Four Five Six
[/php]

On the 4th example, We use “s” patter modifier. If you try this without “s”, you see that it does not work.

Pattern Modifiers

s: If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. (more info about Pattern Modifiers)