this is my code:
if(!preg_match($address_base,$value)){
echo "if not preg_match" . "<br />";
$value= $address . $value;
echo "final value: ", $value . "<br />";
}
What I want it to do is; if $value does’nt include $address_base, add $address_base to the value.
$address_base is an web address without http:// and trailing slashes, and $value is something like;
12.jpg, www.example.com/12.jpg, http://www.example.com/12.jpg
regarless of the $value, my code executes as if $value does’t include $address_base.
How can I do it?
<?php
$url = "http://google.com";
$value = htmlspecialchars($url);
if (!preg_match("/^(https?:\/\/+\w\-]+\.\w\-]+)/i",$value))
{
echo "URL is not valid.<br>";
echo $value;
}
else
{
echo "Its valid URL.<br>";
echo $value;
}
?>
The 1st argument must be a pattern to validate the $value.
Assume that $url is coming from a form and you can change it to $_POST’url’].
$url = $_POST'url'];
If saving it in database, i would suggest to filter it by mysql_real_escape_string.
$url = mysql_real_escape_string($_POST'url']);
If you are using mysqli, then:
$url = mysqli_real_escape_string($_POST'url']);
Other than that you can modify the code to suit your need.
PHP: preg_match - Manual
Good Luck
To be honest, I am not so good at regexes. Can you explain ^(https?://+\w-]+.\w-]+)/i a little bit more. Especially, +\w-]+.\w-]+ this part and “i” at the and?
\w : Matches any of the following characters: A-Z, a-z, 0-9, and underscore. Equivalent to [A-Za-z0-9_].
- : Matches hyphens.
\anything : Anchors and sequences
/i : Its a modifier and can be used to turn on the insensitivity for the remainder of the regular expression.
I admit, these regex things are a little hard to understand.
I found this guide, hope will help you understanding the basic operators, modifiers etc.
Regular Expression Basic Syntax Reference
Hmm, really nice reference guide, definetely going for bookmarks. By the way, I write a simple php code for self development, if you want to check that and comment:
my php trial