Page 1 of 1

preg_match: ensure the start and the end contains something

Posted: Mon Aug 16, 2010 8:00 pm
by lauthiamkok
Hi,

I want to have the regular expression that makes sure the beginning of the string contains 'http://' and '/' and the end.

This is a longer version I came up with,

Code: Select all

if(!preg_match("/(^http:\/\//", $site_http)) 
{
	$error = true;
	echo '<error elementid="site_http" message="site_http - Your link appears to be invalid. Please confirm that your link contains http:// at the start."/>';
}
elseif (!preg_match("/\/$/", $site_http)) 
{
	$error = true;
	echo '<error elementid="site_http" message="site_http - Your link appears to be invalid. Please confirm that your link has ended with a /."/>';
}
but I thought these two expressions can put together like below, but it wont work,

Code: Select all

if(!preg_match("/(^http:\/\/)&(\/$)/", $site_http)) 
{
	$error = true;
	echo '<error elementid="site_http" message="site_http - Your link appears to be invalid. Please confirm that your link contains http:// at the start and a / at the end."/>';
}
the multiple expressions that I try to combine must be wrong! any idea?

thanks,
Lau

Re: preg_match: ensure the start and the end contains someth

Posted: Mon Aug 16, 2010 10:03 pm
by requinix
No need for regular expressions.

Code: Select all

if (strncmp($site_http, "http://", 7) != 0 || $site_http[strlen($site_http) - 1] != "/") {

Re: preg_match: ensure the start and the end contains someth

Posted: Tue Aug 17, 2010 4:12 am
by amargharat
Use following code,

Code: Select all

preg_match('/^http\:\/\/(.*?)\/$/', 'http://www.google.com/', $matches);
if($matches)
	echo "contains 'http://' at the start and '/' at the end";
else
	echo "no matches found";

Re: preg_match: ensure the start and the end contains someth

Posted: Tue Aug 17, 2010 5:51 am
by lauthiamkok
tasairis wrote:No need for regular expressions.

Code: Select all

if (strncmp($site_http, "http://", 7) != 0 || $site_http[strlen($site_http) - 1] != "/") {
this is a good trick! thanks alot! :D

Re: preg_match: ensure the start and the end contains someth

Posted: Tue Aug 17, 2010 5:52 am
by lauthiamkok
amargharat wrote:Use following code,

Code: Select all

preg_match('/^http\:\/\/(.*?)\/$/', 'http://www.google.com/', $matches);
if($matches)
	echo "contains 'http://' at the start and '/' at the end";
else
	echo "no matches found";
thanks so much for this! :D