I'm trying to strip the "http://" from the front of a URL that is input into a form, but having some trouble with the regex.

Here is the lin of code I have:

if(preg_match("^http:\/\/$",$_POST['homepage_url'])){ $_POST['homepage_url'] = preg_replace("^http:\/\/$","",$_POST['homepage_url'],1); }

and here is the error message:
Warning: No ending delimiter '' found on line 6

Regex's are probably the one thing in PHP (and PERL) that I still have trouble with on a regular basis.

Thanks
- keith

    I'm not too familiar with regular expression, but you could use str_replace to do this

    $homepage_url = str_replace("http://", "", $_POST['homepage_url']);

    Cgraz

      By the way, this warning
      Warning: No ending delimiter '' found on line 6
      means that you forgot to put delimiters around the regex. Remember in Perl you had to put your regex in between / /? e.g. /.*/
      Well, same thing with PHP:
      preg_match('/your regex expr here/', $str) and same with preg_replace. Difference between Perl and PHP is that in PHP the regex needs to be a string, so you also need quotes around it.

      Diego

        Hello ,

        Try this , it will work ...

        <?
        $_POST['homepage_url']="http://www.mandesh.com";
        if(preg_match("/^(http:\/\/)?([^\/]+)/i",$_POST['homepage_url'],$matchfound))
        { 
        	preg_match("/[^\.\/]+\.[^\.\/]+$/",$matchfound[2],$finalmatch);  //for domainname
        }
        //$_POST['homepage_url'] = $finalmatch[0];
        print " Input URL	: ".$_POST['homepage_url']."<br>";
        print "After strip	: ".$matchfound[2]."<br>";
        print " doamin name : ".$finalmatch[0]; 
        
        ?>
        

          Nah, the solution by cgraz would be the best. Either that one or

          $homepage_url = $_POST['homepage_url'];
          if(substr($homepage_url,0,7)=='http://')
              $homepage_url = substr($str,7);
          

          Whichever; hauling out an entire regular-expression engine for this task is serious overkill.

            This is what works now. Thanks to diego for pointing out my oversight. All I needed was the // enclosing the regex.

            $string = "http://www.domain.com";
            if(preg_match("/^http:\/\//",$string)){ $string = preg_replace("/^http:\/\//","",$string,1); }
            

            As for which is best to use, a regex or substr(). I only used the regex because I want to get better at regex's. I know that this could easily be done with str_replace. As a matter of fact, I plan on using str_replace in the script, I was just trying to do it with the regex to detect if it actually had the [url]http://[/url] in it or not.

            • keith
              Write a Reply...