If string contains forward slash - php

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!";
}

Related

startsWith Case sensitive

Can't find a solution to this which seems simple enough. I have user input field and want to check the user has prefixed the code asked for with an S (example code S123456 so I want to check to make sure they didn't just put 123456).
// Function to check string starting with s
if (isset($_REQUEST['submitted'])) { $string=$_POST['required_code'];function startsWith ($string, $startString){$len = strlen($startString);return (substr($string, 0, $len) === $startString);
}
// Do the check
if(startsWith($string, "s"))echo "Code starts with a s";else echo "Code does not start with a s";}
The problem is if the user inputs an upper case S this is seen as not being a lower case s.
So I can get round this using
$string = strtolower($string);
So if the user inputs an uppercase S it gets converted to lower case before the check. But is this the best way? Is there not someway to say S OR s?
Any suggestions?
What you could do instead of creating your own function, is using stripos. Stripos tries to find the first occurrence of a case-insensitive substring.
So as check you could have:
if(stripos($string, "s") === 0)
You need 3 equal signs, since stripos will return false (0) if it can't find the substring.
Take your pick; there are many ways to see if a string starts with 'S'. Some of them case-sensitive, some not. The options below should all work, although I wouldn't consider any of them better than your current solution. stripos() is probably the 'cleanest' check though. If you need multibyte support, there's also the mb_stripos() variant.
(Although; keep in mind that stripos() can also return false. If you're going with that option, always use the stricter "identical" operator ===, instead of == to prevent type juggling.)
if (stripos($string, 's') === 0) {
// String starts with S or s
} else {
// It does not
}
if (str_starts_with($string, 's') || str_starts_with($string, 'S')) // ...
if (in_array(substr($string, 0, 1), ['S', 's'], true)) // ...
if (preg_match('/^s/i', $string)) // ...
// Many other regexp patterns also work
Thanks all, it was
if (str_starts_with($string, 's') || str_starts_with($string, 'S')) // ...
I was looking for I had tried
if (str_starts_with($string, 's' || 'S')) // ...

exact preg_match with #

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#');

How to disable ' - ; : ~ ` from input and remove from string?

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.

what is equivalent of =~ of ruby in php?

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

Check if a string does not contains a specific substring [duplicate]

This question already has answers here:
How do I check if a string contains a specific word?
(36 answers)
Closed 26 days ago.
In SQL we have NOT LIKE %string%
I need to do this in PHP.
if ($string NOT LIKE %word%) { do something }
I think that can be done with strpos()
But can’t figure out how…
I need exactly that comparission sentence in valid PHP.
if ($string NOT LIKE %word%) { do something }
if (strpos($string, $word) === FALSE) {
... not found ...
}
Note that strpos() is case sensitive, if you want a case-insensitive search, use stripos() instead.
Also note the ===, forcing a strict equality test. strpos CAN return a valid 0 if the 'needle' string is at the start of the 'haystack'. By forcing a check for an actual boolean false (aka 0), you eliminate that false positive.
Use strpos. If the string is not found it returns false, otherwise something that is not false. Be sure to use a type-safe comparison (===) as 0 may be returned and it is a falsy value:
if (strpos($string, $substring) === false) {
// substring is not found in string
}
if (strpos($string, $substring2) !== false) {
// substring2 is found in string
}
use
if(stripos($str,'job')){
// do your work
}
<?php
// Use this function and Pass Mixed string and what you want to search in mixed string.
// For Example :
$mixedStr = "hello world. This is john duvey";
$searchStr= "john";
if(strpos($mixedStr,$searchStr)) {
echo "Your string here";
}else {
echo "String not here";
}
Kind of depends on your data, doesn't it? strpos('a foolish idea','fool') will show a match, but may not be what you want. If dealing with words, perhaps
preg_match("!\b$word\b!i",$sentence)
is wiser. Just a thought.

Categories