通过查找字符串PHP的特定部分从字符串中删除行

问题描述:

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.

我需要帮助使用PHP处理一个String。 p>

字符串示例: strong> p>

 这是行
这是第二行
这是第三行
xyz下一行
这是第五行
  code>   pre> 
 
 

如何使用“xyz” strong>删除行开头而不使用字符串函数 explode() code>并比较每行的开头? p>

我只需找到“xyz”并删除此行即可。 我希望存在更简单的解决方案,比如每行比较爆炸。 p> div>

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

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

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

There are at least 2 ways:

Fast:

  • find " xyz" with strpos() function and store the position as start
  • find find 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);