I have Googled and looked at a lot of threads on this subject but none answers this issue for me. I have even copied several different filter strings that do the same thing into do my simple validation. They all work on www.functions-online.com/preg_match.htm but none of them are working in my if() statement.
PHP ver. 5.3.3
My code to allow for only Alpha-Numaric and spaces:
$myString = 'My Terrific Game';
if (!preg_match('/^[a-z0-9\s]+$/i', $myString)) { "$errorMessage }
I have even reduced the filter to '/^[a-z]+$/' and the test string to 'mytarrificgame' and it still returns zero. It's as if preg_match() isn't functioning at all.
Anyone have any suggestions?
Some things you need to correct:
You have unclosed quotes in "$errorMessage. It should be $errorMessage or "$errorMessage".
There is no command there. If you want to print the value, use echo $errorMessage.
And is that variable being set anywhere in the code?
This should work
if (!preg_match('/^[a-z0-9\s]+$/i', $myString)) { echo $errorMessage; }
Or, if you think about it, matching only 1 character outside of those allowed should be enough.
Code:
$myString = 'My Terrific Game';
$errorMessage = 'ERROR: Unallowed character';
if (preg_match('/[^a-z0-9\s]/i', $myString)) {
echo $errorMessage;
} else {
echo 'Valid input';
}
ideone Demo
I tried the filter string shown in the 2nd example of the first answer above and it didn't even work on the on-line test page but it did give me a new starting place to solve my dilemma. When I moved the carrot to before the opening bracket, it kind of works but flaky. After trying different things I finally got back to my original '/^[a-z0-9\s]+$\i' and it started working rock solid. I think the reason that it wouldn't work at all for me before is that I was expecting a boolean test on the preg-match() expression to accept a zero as false. This is probably a php version 5.3.3 thing. I tried the following;
if(preg-match('/^[a-z0-9\s]+$/i', $testString) === 0) { "Do Something" }
It is now working. By looking deep into the preg-match() description, I found that it only returns a boolean false if an error occurred. A valid no-match returns a zero.
Thanks to all who looked here and considered my problem.
Related
I'm looking at this: https://www.php.net/manual/en/reserved.php
I've made numerous search queries for things like: "php determine if string is reserved keyword".
I find nothing, and I'm starting to seriously sweat. Please don't tell me I'm going to have to code a complicated script to regularly scrape the PHP manual for all these various kinds of reserved keywords and build my own database!
Please let there be a nice, simple function to simply check:
var_dump(is_reserved_php_keyword('if'));
And it gives a true/false.
I went a different way to Andrew and instead went for having PHP figure it out rather than hard coding the list.
function isPhpKeyword($testString) {
// First check it's actually a word and not an expression/number
if (!preg_match('/^[a-z]+$/i', $testString)) {
return false;
}
$tokenised = token_get_all('<?php ' . $testString . '; ?>');
// tokenised[0] = opening PHP tag, tokenised[1] = our test string
return reset($tokenised[1]) !== T_STRING;
}
https://3v4l.org/WA6dr
This has a few advantages:
It doesn't need the list to be maintained as PHP's own parser says what's valid or not.
It's a lot simpler to understand.
Unfortunately, I'm not aware of any built-in function for what you describe. But based on the RegEx pattern you can find among the contributed notes on PHP.net, you can test it like this:
$reserved_pattern = "/\b((a(bstract|nd|rray|s))|(c(a(llable|se|tch)|l(ass|one)|on(st|tinue)))|(d(e(clare|fault)|ie|o))|(e(cho|lse(if)?|mpty|nd(declare|for(each)|if|switch|while)|val|x(it|tends)))|(f(inal|or(each)?|unction))|(g(lobal|oto))|(i(f|mplements|n(clude(_once)?|st(anceof|eadof)|terface)|sset))|(n(amespace|ew))|(p(r(i(nt|vate)|otected)|ublic))|(re(quire(_once)?|turn))|(s(tatic|witch))|(t(hrow|r(ait|y)))|(u(nset|se))|(__halt_compiler|break|list|(x)?or|var|while))\b/";
if(!preg_match($reserved_pattern, $myString)) {
// It is not reserved!
};
It may not be the most elegant-looking piece of PHP code out there, but it gets the job done.
UPDATE: See online demo of function here: https://3v4l.org/CdIjt
I got a problem with string comparing in php, and i've done research thoughout te internet to no avail. So it's my turn asking the questions:
The following is my code for comparing two strings, one from my database, and one from an irc chat. The problem is that this code won't compare correctly
if('!gt' == $command)
^this don't work, neither do:
if(stripos('!gt', $command) === 0){
echo "This is the correct command<br>";
privmsg($channel, $GLOBALS['commands'][$i]['message']);
}
IRC input ($command) = !gt
My question is ultimately: Why doesn't !gt equal to !gt with the stripos() function?
It seems like i got some extra characters with the string, so i had to use:
trim(string)
to remove the extra characters.
A big thanks to #rizier123, #MarkBaker and #AbraCadaver for the help :D
Alright so I've already created a PHP bug about this but it was marked as bogus, but I can't help but to believe they didn't read it carefully...
Link to Bug #54042
The error is caused by using an include() statement in an IF statement, making the statement believe it's been passed an empty string.
Reviewing the bug will explain everything, including a test script.
Is it a bug, or am I missing something "feature"-wise? This is weird seeing as how assigning the output of include to a variable and then testing that value works just fine (which would be the workaround).
Well, the documentation says:
Because include() is a special language construct, parentheses are not needed around its argument. Take care when comparing return value.
<?php
// won't work, evaluated as include(('vars.php') == 'OK'), i.e. include('')
if (include('vars.php') == 'OK') {
echo 'OK';
}
// works
if ((include 'vars.php') == 'OK') {
echo 'OK';
}
?>
So this behaviour is already known and not considered as a bug. You even have an explanation why it works this way:
include does not need parenthesis, so PHP does not really whether you want to do:
include('vars.php')
or
include(('vars.php') == 'OK')
It seems that it is implemented to interpet it as the latter (something like the longest possible match).
Same goes for
$v = include('foo') . 'bar';
which PHP interprets as
$v = include(('foo') . 'bar');
and tries to load foobar.
But the solution is also given: Wrap the whole include statement into parenthesis, then there is only one way how PHP can interpret the call:
$v = (include ('foo')) . 'bar';
(Maybe) off topic: You will find similar "issues" in other parts of PHP. Take variable variables:
$obj->$foo['bar'];
PHP does not know whether you want to access the bar element of the array $foo and use this value as property name:
$obj->{$foo['bar']};
or if you want to access the bar element of $obj->$foo:
{$obj->$foo}['bar'];
In all these cases, there is a default behaviour of the parser. The developers decided for one possibility because they had to. It might not be what you expect, but if you know it, you can deal with it.
This behaviour cannot simply be changed as it might break code that relies on this behaviour.
The CMS I'm using has a plugin that pulls a series of pages based on how you've tagged those pages. Everything is working fine, but I need to display the number of pages returned after a user sends a query.
The variable that the number of records is stored in is a string. The small script I'm writing tries to check if this string is blank, and if so echo nothing, but if it's not blank echo the number of pages returned.
<?php
if ($count !== ''){
echo "text";
}
?>
However, whenever it's passed when the string is supposed to be empty it treats it as if it is not. I'm not sure what I'm doing wrong or what the string contains that it's not empty.
I found a resource about converting strings to integers but it set it to 0. Thanks for any help.
$count will never be equal to ' ' if you trim it before.
It cannot be equal to ' ' after trim, you should check if it is equal to an empty string and not a string with a white space. (trim deletes white spaces)
trim — Strip whitespace (or other characters) from the beginning and end of a string
http://php.net/manual/en/function.trim.php
trim removes all spaces, so $count == ' ' will always be false if you trimmed first. The easiest change to your code would be to replace the ' ' with ''. Or you could just do this: echo trim($count) === '' ? '' : "text";
trim() is going to remove all white-space characters from the beginning and end of the string. Unless there is content in the middle, you'll likely end up with a completely empty string. If you're testing for this, try checking empty() or is_null().
if (empty($string)) {
echo "String is empty.";
}
I find it's better using built-in functions instead of hard-coding a =='' comparison.
Use var_dump() to check the type and the content of the variable.
Check the manual
Your code seems wrong; you've got "!==", where I'd swear you need to have "!=" (only one equals sign). I'm not sure what "!==" would evaluate to, but I'd bet it's not what you want.
It seems from the comments that your "blank" string is not blank, but instead has something odd in it. Assuming that it's not too odd I'd just try this:
$count = intval($count);
if ($count) {
echo 'text';
}
Though this assumes that the $count actually looks like a number to intval when it's got a number in it -- we may need to take a look at this "string" you're getting back in more detail to figure out what's really in it.
Hopefully you've already taken the advice given by others and looked at the resulting page source after doing a var_dump() -- otherwise I'd guess that $count has XML in it, or something else that won't render well if you dump it to an HTML page and view the page rather than the source...
If nothing else, you could really try brute-forcing it:
$count = intval(preg_replace('/[^\d]/', '', $count));
if ($count) {
echo 'text';
}
...but really it'd be better to work out what this odd plug-in is giving you, and why. Which CMS and plugin is it? Are there some docs available for this thing that's returning $count to you? Do you have the plugin source?
This is the preg_match i am trying to use to find specific text in text file.
if (preg_match($regexp,$textFile,$result) > 0) {
echo "Found ".$result[0];
} else {
echo "Not found";
}
However, the result is always Found and nothing more. The result array is empty. Now i read that preg_match can't work with long strings.
My text file is about 300KB so thats 300000 characters i guess.
I am 100% sure that the searched string is in the text file, and the fact that preg_match function returns value above 0 means it found it, but it didn't place it into the result array somehow.
So my question would be, how do i make it work?
regexp would be /[specific text]\{(\d*)\}/ so, of course i want to be able to get the number in the parentheses.
You'll be glad I found this question. As of PHP 5.2, they introduced a limit on the size of text that the PCRE functions can be used on, which defaults to 100k. That's not so bad. The bad part is that it silently fails if greater than that.
The solution? Up the limit. The initialization parameter is pcre.backtrack_limit.
No, don't up the pcre limit. Don't do things without understand them. This is a common bug with php pcre
Read this awesome answer by #ridgerunner :
https://stackoverflow.com/a/7627962/1077650
this class of regex will repeatably (and silently) crash Apache/PHP with an unhandled segmentation fault due to a stack overflow!
PHP Bug 1: PHP sets: pcre.recursion_limit too large.
PHP Bug 2: preg_match() does not return FALSE on error.