PHP regex expression to find if a string contains YYYY-MM-DD - php

I would like to check if a URL (or any string) contains any form of the following pattern ####-##-##
Does anyone have a handy str_replace() or regular expression to do that?
something like:
contains_date_string($string);
returns true if $string contains ####-##-##
Thank you!!!

if (preg_match('/\b\d{4}-\d{2}-\d{2}\b/', $str)) {
// ...
}
If the word boundary (\b) doesn't do the trick, you could try negative lookbehind and lookaheads:
if (preg_match('/(?<!\d)\d{4}-\d{2}-\d{2}(?!\d)/', $str)) {
// ...
}
As an additional validation, you could use checkdate() to weed out invalid dates such as 9999-02-31 as mentioned in this answer.

Use preg_match in conjunction with checkdate:
function contains_date($str)
{
if (preg_match('/\b(\d{4})-(\d{2})-(\d{2})\b/', $str, $matches))
{
if (checkdate($matches[2], $matches[3], $matches[1]))
{
return true;
}
}
return false;
}

'/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/'
'Makes sure things like 1998-13-32 won't get past and validate.'
I got this from google... http://www.devnetwork.net/viewtopic.php?f=29&t=13795
Looks promising. Hope this will help someone on the search for the same as stackoverflow is the most accessible SEO wise.

The test given here should work:
if (preg_match('#[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|1[0-9]|2[0-9]|3[01])#', $str)) {
// do something
}
Whatever regex you choose, be careful! When a machine sees 2004-04-01, it won't be able to distinguish between January 4th and April Fools day unless you tell it otherwise...

Related

check words with preg_match

I have some words with | between each one and I have tried to use preg_match to detect if it's containing target word or not.
I have used this:
<?php
$c_words = 'od|lom|pod|dyk';
$my_word = 'od'; // only od not pod or other word
if (preg_match('/$my_word/', $c_words))
{
echo 'ok';
}
?>
But it doesn't work correctly.
Please help.
No need for regular expressions. The functions explode($delimiter, $str); and in_array($needle, $haystack); will do everything for you.
// splits words into an array
$array = explode('|', $c_words);
// check if "$my_word" exists in the array.
if(in_array($my_word, $array)) {
// YEP
} else {
// NOPE
}
Apart from that, your regular expression would match other words containing the same sequence too.
preg_match('/my/', 'myword|anotherword'); // true
preg_match('/another/', 'myword|anotherword'); // true
That's exactly why you shouldn't use regular expressions in this case.
You can't pass a variable into a string with single quotes, you need to use either
preg_match("/$my_word/", $c_words);
Or – and I find that cleaner :
preg_match('/' .$my_word. '/', $c_words);
But for something as simple as that I don't even know if I'd use a Regex, a simple if (strpos($c_words, $my_word) !== 0) should be enough.
You are using preg_match() the wrong way. Since you're using | as a delimiter you can try this:
if (preg_match('/'.$all_words.'/', $my_word, $c_words))
{
echo 'ok';
}
Read the documentation for preg_match().

String cannot start with zero

I have a string which i want to check with a regex. It is not allowed for it to start with a 0. So please see the following examples:
012344 = invalid
3435545645 = valid
021 = invalid
344545 = valid
etc.
How does this regex look in PHP?
PS. This must be a regex solution!
The REGEX should looks like that :
^[1-9][0-9]*$
PHP Code :
<?php
$regex = "#^[1-9][0-9]*$#";
function test($value, $regex)
{
$text = "invalid";
if(preg_match($regex, $value)) $text = "valid";
return $value+" = "+$text+"\n\r";
}
echo test('012345', $regex);
echo test('12345', $regex);
?>
Well it would be a simple /[1-9][0-9]*/.
Please research your question better next time.
This could have also helped you: Regular expression tester
Edit:
Yeah, the answer got downvoted, because it's missing the anchors and seems to be wrong. For completess' sake, I posted the php code I would use with this regex. And no it's not wrong. It may not be the most elegant way, but I like checking whether the regex matched the whole string afterwards more. One reason is that to debug a regex and see what it actually matched I just have to comment out === $value after return $matches[0]
<?php
function matches($value) {
preg_match("/[1-9][0-9]*/", $value, $matches);
return $matches[0] === $value;
}
//Usage:
if (matches("1234")) {
//...
}
?>

Determining if a URL contains a certain hostname

I need to make a regular expression for php preg_match that does the following matching.
This is the function
function isValidURL($url,$searchfor){
return preg_match("/\b.$searchfor \b/i", $url);
}
I need to find the somedomain.com in the following
Possible Strings entering the function
http://www.somedomain.com
http://somedomain.com
http://www.somedomain.com/anything
http://somedomain.com/anything
http://anything/somedomain.com
So I need a regular expression that does this
http://www.somedomain.com Will Match
http://somedomain.com Will Match
http://www.somedomain.com/anything Will Match
http://somedomain.com/anything Will Match
but
http://anything/somedomain.com Will NOT match
What about using parse_url()?
if( strpos(parse_url($url, PHP_URL_HOST), 'somedomain.com') !== false )
{
// hostname contains 'somedomain.com'.
}
Try this...
$url = "http://komunitasweb.com/";
if (preg_match('/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):? (d+)?/?/i', $url)) {
echo "Your url is ok.";
} else {
echo "Wrong url.";
}
Copied from a google searh on "php url regular expression". Check google out, awesome tool. :-)
All this requires is a placeholder for the URL beginning. Excluding slashes with a negated character class [^/] might already be sufficient:
function isValidURL($url,$searchfor){
return preg_match("~http://[^/\s]*\.$searchfor(/|$|\s)~i", $url);
}
Note that this fails some edge cases, like user:pw# pairs. And no idea if your $searchfor was supposed to contain the TLD already. Also don't forget to preg_quote it.

PHP if/switch concatenated by *

I was wondering if anybody knew if there was a way to concatenate a * (all) to a string inside an if (or switch) statement. For example if you had a URL called /hello/there and /hello/whats-up ... is there anyway you could have something like the following:
if ($url="/hello/" . *) {
sayHello();
} else { sayGoodebye(); }
etc... I don't think that's the correct syntax, but if anybody knows what I'm talking about it would be a great help.
Thanks (:
$match = "/hello/";
if (substr($url, 0, strlen($match)) === $match) {
sayHello();
} else {
sayGoodbye();
}
Do not use regular expressions if you don't have to...
You can also check for the position of $match in the $url string:
$match = "/hello/";
if (strpos($url, $match) === 0) {
sayHello();
} else {
sayGoodbye();
}
Use regular expressions:
http://www.regular-expressions.info/php.html
So it would be something like this:
if (ereg("/hello/", $url)) {
sayHello();
} else { sayGoodebye(); }
Although that would match anything with "/hello/" in it anywhere, so if you only wanted to match strings that start with "/hello/" you'd have to modify the expression. The point is, if you've never used regular expressions it's a good thing to invest some time into. It'll pay off eventually because at some point you're going to need this skill.
Edit: I'll leave my original code here as reference, but please see phihag's comments and use preg_match and the preg_match compatible expression instead of ereg and the expression I used.

Regex to validate only natural numbers?

I recently found out that a method I've been using for validating user input accepts some values I'm not particularly happy with. I need it to only accept natural numbers (1, 2, 3, etc.) without non-digit characters.
My method looks like this:
function is_natural($str)
{
return preg_match('/[^0-9]+$/', $str) ? false : $str;
}
So it's supposed to return false if it finds anything else but a whole natural number. Problem is, it accepts strings like "2.3" and even "2.3,2.2"
perhaps you can clarify the difference between a "number" and a "digit" ??
Anyways, you can use
if (preg_match('/^[0-9]+$/', $str)) {
// contains only 0-9
} else {
// contains other stuff
}
or you can use
$str = (string) $str;
ctype_digit($str);
The problem with /^[0-9]+$/ is that it also accepts values like 0123.
The correct regular expression is /^[1-9][0-9]*$/.
ctype_digit() suffers the same problem.
If you also need to include zero use this regex instead: /^(?:0|[1-9][0-9]*)$/
Use ctype_digit() instead
I got an issue with ctype_digit when invoice numbers like "000000196" had to go through ctype_digit.
So I have used a:
if (preg_match('/^[1-9][0-9]?$/', $str)) {
// only integers
} else {
// string
}

Categories