How can I preg_match exactly with that kind of search:
My value to find: #5#
My value to search: #5#;#9#
I did a simple
if (preg_match("#5#", "#5#;#9#")) { return true; } else { return false; }
And, it returns true.
The problem with that code, it's return also true if my value to compare is #51#;#55# whereas it has to be false in that case:
if (preg_match("#5#", "#51#;#55#")) { return true; } else { return false; }
Also returns true whereas I want false.
preg_match("#5#", "#51#;#55#") returns true because preg_match uses # as delimiter. In order to match #5# you have to add delimiters around the regex:
if (preg_match("/#5#/", "#51#;#55#")) { return true; } else { return false; }
This will return false.
If all you need is to find a string you know (#5#) in another string then the best way is to use function strpos(). It returns the boolean FALSE if it cannot find the string or an integer number that represents the position of the searched string into the other string.
It is faster that any preg_*() function.
$pos = strpos('#5#', '#5#;#9#');
if ($pos !== FALSE) {
echo('Found (at position '.$pos.')');
} else {
echo('Not found.');
}
You have to pay attention to the comparison operator: using $pos != FALSE is not enough because 0 == FALSE. You have to compare using === or !== to avoid this.
Using preg_match()
Your approach failed because in PHP the PCRE functions interpret the first character from the regex as a delimiter.
This means the regex in #5# is: 5. And this regex, of course, matches any 5 it finds in the string. To fix it you have to surround your regex with some delimiter (/ is usually used):
return preg_match('/#5#/', '#5#;#9#');
Related
I tried to add extra security by removing special characters. I want to allow letters, numbers and ? = & only.
I tried:
if (strpos($_SERVER['REQUEST_URI'],'\'')) { echo 'true'; }
I cannot just simply put ' in between the '' as it breaks it so I tried adding the \ but it didn't work.
Is there a way to detect all the symbols in the url string or input field?
EDIT:
tried adding < simply into the list
if (preg_match('#[#*,!$\'\-;:<>~`^|\(\\)\\{\\}\\[\\]]#i', $_SERVER['REQUEST_URI']) || strpos($_SERVER['REQUEST_URI'],'script')) {
echo 'Cannot do that';
}
I tried adding ([\<])([^\>]{1,})*([\>]) into there but it didn't work.
I also tried adding a condition if strcmp($_SERVER['REQUEST_URI'], strip_tags($_SERVER['REQUEST_URI'])) != 0
and when i added into the url, it didn't do anything
Use preg_match to test for anything but the characters you want:
if (preg_match('#[^a-z0-9?=&]#i', $str)) { echo 'true'; }
Use preg_replace to remove them:
$str = preg_replace('#[^a-z0-9?=&]#i', '', $str);
If you just want to prohibit certain characters, use a regular expression that just matches those characters:
if (preg_match('#[\'\-;:~`]#i', $str)) { echo 'true'; }
You can fix that using double quotes as strings delimiter, try this
if (strpos($_SERVER['REQUEST_URI'],"'")) { echo 'true'; }
One thing that none of the posts addressed is why strpos didn't work for you. strpos can return two types. It can return an integer that is greater than or equal to zero. 0 being the first character. It can also return a boolean type false. To check if if strpos found a match it would have to have been written like this:
if (strpos($_SERVER['REQUEST_URI'],'\'') !== false) { echo 'true'; }
From the PHP Documentation The comparison $a !== $b operator works this way:
return TRUE if $a is not equal to $b, or they are not of the same type.
Information on strpos returning two types (boolean false or an integer) can be found in this PHP strpos Documentation. In particular:
Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
So as you can see 0 and false are not the same thing which is why your test failed.
As for security and strings in PHP I recommend you look at this StackOverflow article for some opinions on the matter.
I am a Rubyist trying to implement some of my code in PHP and not able to get the equivalent PHP code for this particular def.Can anyone help me out.Thanks in advance.
def check_condition(str)
str =~ SOME_REGEX
end
In PHP it looks like:
function check_condition($str) {
return preg_match(SOME_REGEX, $str);
}
Unfortunately there is no regex-match operator in PHP unlike some other languages. You'll have to call a function. Follow the manual of preg_match() and the manual page about the so called perl compatible regular expresssions (preg) in general.
Something additional. After reading the manual page of preg_match you know that the method returns an integer, the number of matches found. As the method returns after the first match this can be only 0 or 1. As of the loose typing system of PHP this would be good for using it in loose comparisons like:
if(check_condition($str)) { ....
if(check_condition($str) == true) { ...
But it would not work in a strict comparison:
if(check_condition($str) === true) { ...
Therefore it would be a good idea to cast the return value of preg_match:
function check_condition($str) {
return (boolean) preg_match(SOME_REGEX, $str);
}
Update
I have thought a little bit about my last suggestion and I see a problem with this. preg_match() will return an integer if all is working fine but boolean FALSE if an error occurs. For example because of a syntax error in the regex pattern. Therefore you will be not aware of errors if you are just casting to boolean. I would use exceptions to show that an error was happening:
function check_condition($str) {
$ret = preg_match(SOME_REGEX, $str);
if($ret === FALSE) {
$error = error_get_last();
throw new Exception($error['message']);
}
return (boolean) $ret;
}
Have a look at preg_match:
if (preg_match('/regex/', $string) {
return 1;
}
Isn't it preg_match?
function check_condition($str) {
return preg_match(SOME_REGEX,$str);
}
I don't think there is an equivalent.
preg_match returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.
=~however returns the position where the match starts, or nil if there is no match. Since nil is false and all numbers including zero are true, boolean operations are possible.
puts "abcdef" =~ /def/ #=> 3 # don't know how to get this from a RegExp in PHP
puts "Matches" if "abcdef"=~ /def/ #=> Matches
How do i make a if statement which checks if the string contains a forward slash?
$string = "Test/Test";
if($string .......)
{
mysql_query("");
}
else
{
echo "the value contains a invalid character";
}
You can use strpos, which will make sure there is a forward slash in the string but you need to run it through an equation to make sure it's not false. Here you can use strstr(). Its short and simple code, and gets the job done!
if(strstr($string, '/')){
//....
}
For those who live and die by the manual, when the haystack is very large, or the needle is very small, it is quicker to use strstr(), despite what the manual says.
Example:
Using strpos(): 0.00043487548828125
Using strstr(): 0.00023317337036133
if(strpos($string, '/') !== false) {
// string contains /
}
From the PHP manual of strstr:
Note:
If you only want to determine if a particular needle occurs within
haystack, use the faster and less memory intensive function strpos()
instead.
Use strpos()
If it doesn't return false, the character was matched.
I compared strpos() results with 0. Somehow comparison with false did not work for me.
if (strpos($t, '/') !== 0) {
echo "No forward slash!";
}
I am looking for function which does this option:
preg_match("/^{$STRING}/i", ...)
but, without regular expression, and there must be the ^ in the first, which means that this expression will be false:
$search = "hi", $search_in "ahi";
it must be at the start of the string.
Not sure I understood your request well... But... Try this:
/** Checks if a target string (haystack) starts with a specified string (needle) */
function startsWith($haystack, $needle) {
return (stripos($haystack, $needle) === 0);
}
/* Usage */
startsWith("ahi", "hi"); // Returns FALSE
startsWith("ahi", "ah"); // Returns TRUE
Please note that you need to use 3 = signs, because the function will return false when there is no match in the string.
http://php.net/manual/en/function.stripos.php
if(stripos($search_in, $search) === 0) {
echo "matched";
}
stripos($haystack, $needle) === 0
The exact function for that purpose is strncasecmp. I have no idea why everyone is so bent on stripos workarounds recently.
Albeit it needs the string length for comparison, and the result must be negated for positive matches
if (!strncasecmp($string, "search", 6)) {
The advantage is that it really only compares the first 6 characters. It does not search the whole subject and require an extra comparison afterwards. (Stupid if used as microoptimization. But it's the exact function for that task.)
function startsWithi($haystack, $needle)
{
return substr(strtolower($haystack), 0, strlen($needle))) === $needle;
}
I'm trying to implement the function below. Would it be best to use some type of regex here? I need to capture the number too.
function endsWithNumber($string) {
$endsWithNumber = false;
// Logic
return $endsWithNumber;
}
return is_numeric(substr($string, -1, 1));
This only checks to see if the last character in the string is numerical, if you want to catch and return multidigit numbers, you might have to use a regex.
An appropriate regex would be /[0-9]+$/ which will grab a numerical string if it is at the end of a line.
$test="abc123";
//$test="abc123n";
$r = preg_match_all("/.*?(\d+)$/", $test, $matches);
//echo $r;
//print_r($matches);
if($r>0) {
echo $matches[count($matches)-1][0];
}
the regex is explained as follows:
.*? - this will take up all the characters in the string from the start up until a match for the subsequent part is also found.
(\d+)$ - this is one or more digits up until the end of the string, grouped.
without the ? in the first part, only the last digit will be matched in the second part because all digits before it would be taken up by the .*
To avoid potential undefined index error use
is_numeric($code[strlen($code) - 1])
instead.
in my opinion The simple way to find a string ends with number is
$string = "string1";
$length = strlen($string)-1;
if(is_numeric($string[$length]))
{
echo "String Ends with Number";
}
Firstly, Take the length of string, and check if it is equal to zero (empty) then return false. Secondly, check with built-in function on the last character $len-1.
is_numeric(var) returns boolean whether a variable is a numeric string or not.
function endsWithNumber($string){
$len = strlen($string);
if($len === 0){
return false;
}
return is_numeric($string[$len-1]);
}
Tests:
var_dump(endsWithNumber(""));
var_dump(endsWithNumber("str123"));
var_dump(endsWithNumber("123str"));
Results:
bool(false)
bool(true)
bool(false)
This should work
function startsWithNumber(string $input):bool
{
$out = false; //assume negative response, to avoid using else
if(strlen($input)) {
$out = is_numeric($input[0]); //only if string is not empty, do this to avoid index related errors.
}
return $out;
}