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.
Related
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().
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")) {
//...
}
?>
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...
Really quick noob question with php:
I'm trying to create a conditional statement where I can check if a variable partially matches a substring.
More specific in my case:
$cal is the name of a file, I want it so if $cal contains ".cfg" it echos some text.
pseudocode:
<?php if ($cal == "*.cfg")
{
echo "Hello ";
}
?>
if (strpos($cal, ".cfg") !== false)
{
echo "some text";
}
EDIT
My proposal for matching exactly "*.cfg":
$cal = "abc.cfgxyz";
$ext = "cfg";
if (strrpos($cal, ".".$ext) === strlen($cal)-strlen($ext)-1)
{
echo "matched";
}
In this case, you can simply look at the last four characters of $cal using substr:
if (substr($cal, -4) === '.cfg') {
echo "Hello ";
}
You should look into regular expressions for more complex problems.
if ( preg_match('/\\.cfg$/',$cal) ) echo "Hello ";
should to it. (Assuming you want to match the end of the input string, otherwise, leave out the $)
for simple patterns strpos will do nicely.
if (strpos ('.cfg', $string) !== false)
{
// etc
}
For more complicated parterns, you want preg_match, which can compare a string against a regular expression.
if (preg_match ('/.*?\.cfg/', $string))
{
// etc
}
The former offers better performance, but the latter is more flexible.
You can use various approaches here. For example:
$cal = explode('.', $cal);
if(last($cal) === "cfg")) {
echo "Hello";
}
Or using regular expressions (which are probably way slower than using strpos for example):
if(preg_match("/\.cfg$", $cal)) {
echo "Hello";
}
I honestly don't know how the explode() version compares to substr() with a negative value (lonesomeday's answer) or strpos() (which has its flaws, Frosty Z's answer). Probably the substr() version is the fastet, while regular expressions are the slowest possible way to do this).
The code below gives me this mysterious error, and i cannot fathom it. I am new to regular expressions and so am consequently stumped. The regular expression should be validating any international phone number.
Any help would be much appreciated.
function validate_phone($phone)
{
$phoneregexp ="^(\+[1-9][0-9]*(\([0-9]*\)|-[0-9]*-))?[0]?[1-9][0-9\- ]*$";
$phonevalid = 0;
if (ereg($phoneregexp, $phone))
{
$phonevalid = 1;
}else{
$phonevalid = 0;
}
}
Hmm well the code you pasted isn't quite valid, I fixed it up by adding the missing quotes, missing delimiters, and changed preg to preg_match. I didn't get the warning.
Edit: after seeing the other comment, you meant "ereg" not "preg"... that gives the warning. Try using preg_match() instead ;)
<?php
function validate_phone($phone) {
$phoneregexp ='/^(\+[1-9][0-9]*(\([0-9]*\)|-[0-9]*-))?[0]?[1-9][0-9\- ]*$/';
$phonevalid = 0;
if (preg_match($phoneregexp, $phone)) {
$phonevalid = 1;
} else {
$phonevalid = 0;
}
}
validate_phone("123456");
?>
If this is PHP, then the regex must be enclosed in quotes. Furthermore, what's preg? Did you mean preg_match?
Another thing. PHP knows boolean values. The canonical solution would rather look like this:
return preg_match($regex, $phone) !== 0;
EDIT: Or, using ereg:
return ereg($regex, $phone) !== FALSE;
(Here, the explicit test against FALSE isn't strictly necessary but since ereg returns a number upon success I feel safer coercing the value into a bool).
It's the [0-9\\- ] part of your RE - it's not escaping the "-" properly. Change it to [0-9 -] and you should be OK (a "-" at the last position in a character class is treated as literal, not part of a range specification).
Just to provide some reference material please read
Regular Expressions (Perl-Compatible)
preg_match()
or if you'd like to stick with the POSIX regexp:
Regular Expression (POSIX Extended)
ereg()
The correct sample code has already been given above.