Question

I need help with working with one String using PHP.

String Example:

This is line
this is second line
this is third line
xyz next line
this is fifth line

How to delete line starts with "xyz" without using string function explode() with comparing beginning of each row?

All I need is to find "xyz" and delete this row to end. I hope that exist simpler solution like explode with comparing each row.

Was it helpful?

Solution

If explode() is banned, dare I suggest using regular expressions?

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

This will match a line beginning with xyz and delete up to the next line break.

OTHER TIPS

There are at least 2 ways:

Fast:

  • find "\nxyz" with strpos() function and store the position as start
  • find find \n after the start position
  • get substring usnig substr substr() and store it
  • repeat
  • cut substrings using str_replace(substrs_array, '', text)

Handy:

use Regular Expressions $text = preg_replace('/^xyz.*$/g', '', $string);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top