Forum Moderators: coopster
I need help writing a code that will check if the first characters are http. I am accepting web addresses but don't want any values entered with the [....]
Thanks,
Matt
There's probably a much better way using regular expressions, but they're not my strong point.
Good stay away from them unless you need to use them for some reason they're often overused (even by myself, although I keep trying to break the habit) and are processor intensive, when there's often a much more efficient way to do things...
@ weddingm
There's a few ways to do what you asked... Personally, I would probably be inclined to just str_replace("http://","",$submittedURL); them rather than making the person entering them change anything, but if you want to just check the start, you could use what Tommybs posted or if(strpos($submittedURL,"http")) { /* bad URL */ }
else { /* good URL */ }
The preceding is also case insensitive, but, personally, I would use Tommybs' example with a slight variation:
$submittedURL=strtolower($submittedURL);
str_replace("http://","",$submittedURL);
The reason for the adjustment is by changing the string to lowercase and storing it as the variable you don't ever have to worry about a cap (or all caps) in the submitted URL, whether the URL is HTTP://www.example.com or, 'Oops, I hit (or like) caps lock' WWW.EXAMPLE.COM
and are processor intensive
when there's often a much more efficient way to do things...
This is a much better argument. Just remember there is more than one way to skin a cat. Do what you are comfortable with, if performance becomes an issue and is traced to your regex you can easily refactor your code.
JC
I am accepting web addresses but don't want any values entered with the [.<...]Do you also want to nix https? :-)
Something you probably can't do with string functions without using an "or" and two conditions (or maybe ye' can, too tired to look it up . . . )
$string = preg_replace('/https*\s*:\/\s*\//i','',$string);
The * means "zero or more" so will work for both http or https, i modifier makes it case insensitive: [....] The zero or more space patterns help prevent circumnavigating an exact match (which would probably break the link anyway, but you know users . . . )