Search code examples
phpregexpreg-replacepreg-match

php add action to form tag if not exists


I have the following form tag

$content = '<form action="link.php" method="post" class="form-inputs">';
$content1 = '<form method="post" class="form-inputs">';

so using my regex code :

preg_replace("~<form\s(.|\n)*?>~i",'<form action="linkafterreplace.php" method="post">', $content);

When I use this code for both $content and $content1 this is what I get:

<form action="linkafterreplace.php" method="post">

and the problem is my code can't get class attributes or id attributes . what I want is :

<form action="linkafterreplace.php" method="post" class="form-inputs">

ps : I'm replacing many urls so every url has its own class attribute so it might not be form-inputs


Solution

  • Your regex is currently grabbing the entire form tag and replacing it with the

    <form action="linkafterreplace.php" method="post">
    

    The best way to fix this is to just check for the existence of

    <form
    

    and replace it with

    <form action="linkafterreplace.php" method="post"
    

    The call you need for that is (I haven't tested it as I'm on a computer without PHP):

    preg_replace("~<form~i",'<form action="linkafterreplace.php" method="post"', $content);
    

    Hope that makes sense...


    EDIT:

    Because of the comments, I'm modifying my answer slightly. Again, I don't have a computer with PHP so the syntax may be slightly off.

    The easiest way is to check if the form tag has an action element is to use preg_match, like so:

    if (preg_match("~action=~i")) {    // Check to see if you find "action="
        preg_replace("~action=\".*\"~i", "action='linkafterreplace.php'", $content); // IFF so, replace it using regex.
    } else {
        preg_replace("~<form~i",'<form action="linkafterreplace.php"', $content); // Otherwise add it it.
    }
    

    I am simply using regex to check for the existance of the "action=" inside of the form element. If so, I use a regex replace to put in the new file name. Otherwise, I use regex to add to the beginning like in my original answer.

    Hope that works better for you!