How can I delete a line from a string in PHP by matching a specific substring?

Solution 1:

If you cannot use explode(), you can use a regular expression to remove lines starting with xyz:


$string = preg_replace('/\nxyz.*/', '', $string);

Explanation:

/\nxyz.*/ – matches a newline character followed by xyz and the rest of the line.

preg_replace() – replaces the matched line with an empty string, effectively removing it.

✅ This approach is ideal when you need to filter lines without splitting the string into an array.

Solution 2:

There are two main approaches to remove lines starting with xyz:

1. Using strpos() and substr() (manual method)


$pos = 0;
$substrings = [];

while (($start = strpos($string, "\nxyz", $pos)) !== false) {
    $end = strpos($string, "\n", $start + 1);
    if ($end === false) $end = strlen($string);
    $substrings[] = substr($string, $start, $end - $start);
    $pos = $end;
}

// Remove all matched substrings
foreach ($substrings as $substr) {
    $string = str_replace($substr, '', $string);
}

How it works:

Find the position of \nxyz.

Find the next newline after that.

Extract the substring and store it.

Remove all stored substrings from the original string.

2. Using Regular Expressions (simpler and faster)


$string = preg_replace('/^xyz.*$/m', '', $string);

Explanation:

/^xyz.*$/m – matches lines that start with xyz.

The m flag makes ^ and $ match the start and end of each line, not the whole string.

preg_replace() removes all matching lines in one step.

✅ Tip: The regex method is usually cleaner and faster, especially for multi-line strings.