Need help with regular expression. I practice on replacing code in files with the help of regulars. There is a code in the file:

$list = array(); $list[] = '<form method="POST" action="edit"> <a href="title1">Title 1</a> <input type="submit" name="red" value="Edit Page"> <input type="hidden" name="hidden" value="title1"> <input type="hidden" name="prev" value="'.$_SERVER["REQUEST_URI"].'"> </form> <form method="POST" action=""> <input type="hidden" name="hidden_delete" value="title1"> <input type="submit" name="red" value="Delete Page"><hr> </form>'; $list[] = '<form method="POST" action="edit"> <a href="title2">Title 2</a> <input type="submit" name="red" value="Edit Page"> <input type="hidden" name="hidden" value="title2"> <input type="hidden" name="prev" value="'.$_SERVER["REQUEST_URI"].'"> <hr> </form> <form method="POST" action=""> <input type="hidden" name="hidden_delete" value="title2"> <input type="submit" name="red" value="Delete Page"><hr> </form>'; 

Wrote this replacement:

  $link = 'check.php'; $file = file_get_contents($link); $file = preg_replace('~\$list\[\][^<]+\<.*title1[^;]+\;~s', '', $file); file_put_contents($link, $file); 

What is the essence of the problem. A regular expression removes code from title1 without affecting other code. However, if you put already title2, then both title1 and title2 will be deleted. Please help me fix it to remove only a specific piece of code, that is, either title1 or title2.

  • one
    Why are you in the regular expression escaping the name of the variable, as if it is part of a string, you understand that this is nonsense? And in general, you are trying to replace in the elements of an array, and not preg_replace replaces entries in the string. Do you understand that this is the wrong approach? - Let's say Pie
  • If your lines are part of an array, then you should loop through the array and do the replacement on the elements. In addition, you have an incorrect regular expression. - Let's say Pie
  • one
    Explain why you are storing these strings in an array? - Let's say Pie
  • one
    @ Let'ssayPie, depending on the index, you can output either the first one or the second one. All is obvious-zhezh. A - Architecture! - Manitikyl
  • I only need help with regular) can I do something or not? The fact that it can be constructed incorrectly, I will not even say anything, since only today I took it for the first time. Actually, because I took it, I want to deal with the puzzle that I set for myself, let it be wrong) - Arandar pm

1 answer 1

In general, I figured out this problem. Maybe not quite right, but it works fine. If anyone knows the option better, then write)

 ~\$list\[\][^<]+\<[^>]+\>[^<]+\<[^"]+\"title2\"[^;]+\;~