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.
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
I have the following code/string:
$ids="#222#,#333#,#555#";
When I'm searching for a part using:
if(strpos($ids,"#222#"))
it won't find it. But when I'm searching without the hashes, it works using:
if(strpos($ids,"222"))
I've already tried using strval for the search parameter, but this won't work also.
strpos starts counting from 0, and returns false if nothing is found. You need to check if it's false with === like this...
if (strpos($ids, '#222#') === false) // not found
Or use !== if you want the opposite test...
if (strpos($ids, '#222#') !== false) // found
See the PHP Manual entry for more information
You are not explecitely testing for FALSE when using strpos. Use it like this:
if(strpos($string, '#222#') !== FALSE) {
// found
} else {
// not found
}
Explanation: You are using it like this:
if(strpos($string, '#222#')) {
// found
}
What is the problem with this? Answer: strpos() will return the position in string where the substring was found. In you case 0 as its at the beginning of the string. But 0 will be treated as false by PHP unless you issue an explicit check with === or !==.
It is working as expected. strpos() returns 0 because the string you're searching for is at the beginning of the word. You need to do an equality search:
Update your if() statement as follows:
if(strpos($ids, '#222') !== false)
{
// string was found!
}
Try with this :
$ids="#222#,#333#,#555#";
if(strpos($ids,"#222#") !== false)
{
echo "found";
}
You should use !== because the position of '#222#' is the 0th (first) character.
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 want to know if how can I check I string (specifically an ip address) if that ip address has the string of x
For example
$ip = "66.124.61.23" // ip of the current user
$x = "66.124" // this is the string what I want to check in my $ip.
So how can I check $ip if it has the string of $x?
Please do leave a comment if you are having a hard time understanding this situation.
Thank you.
Use strstr()
if (strstr($ip, $x))
{
//found it
}
See also:
stristr() for a case insenstive version of this function.
strpos() Find the first occurrence of a string
stripos() Find the position of the first occurrence of a case-insensitive substring in a string
You can also use strpos(), and if you're specifically looking for the beginning of the string (as in your example):
if (strpos($ip, $x) === 0)
Or, if you just want to see if it is in the string (and don't care about where in the string it is:
if (strpos($ip, $x) !== false)
Or, if you want to compare the beginning n characters, use strncmp()
if (strncmp($ip, $x, strlen($x)) === 0) {
// $ip's beginning characters match $x
}
Use strstr()
$email = 'name#example.com';
$domain = strstr($email, '#');
echo $domain; // prints #example.com
Based on $domain, we can determine whether string is found or not (if domain is null, string not found)
This function is case-sensitive. For case-insensitive searches, use stristr().
You could also use strpos().
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
Also read SO earlier post, How can I check if a word is contained in another string using PHP?
Use strpos().
if(strpos($ip, $x) !== false){
//dostuff
}
Note the use of double equals to avoid type conversion. strpos can return 0 (and will, in your example) which would evaluate to false with single equals.