STRiSTR not matching data from string - php

Its strange to me, why stristr not matching data? It always print not found
$data = 'Saturday';
$find = 'sat,sun';
if(stristr($data, $find))
echo 'found';
else
echo 'not found';

The stristr() function searches for the first occurrence of a string inside another string. So you need to make the search string different, And for this you need make the $find string to an array and loop through it. That how you can get the sat and sun as different string, and simply use your code to match.
Online Check
$data = 'Saturday';
$find = 'sat,sun';
$find_arr = explode(",", $find);
foreach($find_arr as $find_val){
if(stristr($data, $find_val))
echo 'found';
else
echo 'not found';
}
The result should be for first found and for second not found.

If you find 'Sat', than it will show result Found.
In your case it will consider the 'sat,sun' to one word, so that it will try to find 'sat,sun' in $data and the result will display 'Not Found'.

stristr() find the first occurrence of a string. You can also use preg_match instead of stristr().
Try
<?php
$find = "sat,sun";
$data = 'Sat';
if (preg_match("/\b".$data."\b/i", $find, $match))
print "Match found!";
else
print "not match";
?>

You should use stripos instead of stristr for best results. The stripos function is faster and less memory intensive than stristr.
stripos() returns FALSE if the needle was not found. So if you just need to know if there are ocurrences, use it as follow:
echo stripos($data, 'sat,sun') !== false ? 'found' : 'not found';
Solution code edit from comment request:
To check if your $data value is sat OR sun, do it in a loop:
$data = 'Sunday';
$weekend = 'sat,sun';
$days = explode(',', $weekend);
$index = 0;
$found = false;
while (!$found && isset($days[$index])) {
$found = (stripos($data,$days[$index]) !== false) ? true : false;
$index++;
}
echo $found ? 'found' : 'not found';

Try this one code
$f = 'Saturday';
$data = 'sat,sun';
$find = strtolower(substr($f, 0,3));
$str = stristr($data , $find);
if($str)
echo 'found';
else
echo 'not found';

Related

Check if string contains a value in array [duplicate]

This question already has answers here:
String contains any items in an array (case insensitive)
(15 answers)
Closed 2 years ago.
I am trying to detect whether a string contains at least one URL that is stored in an array.
Here is my array:
$owned_urls = array('website1.com', 'website2.com', 'website3.com');
The string is entered by the user and submitted via PHP. On the confirmation page I would like to check if the URL entered is in the array.
I have tried the following:
$string = 'my domain name is website3.com';
if (in_array($string, $owned_urls))
{
echo "Match found";
return true;
}
else
{
echo "Match not found";
return false;
}
No matter what is inputted the return is always "Match not found".
Is this the correct way of doing things?
Try this.
$string = 'my domain name is website3.com';
foreach ($owned_urls as $url) {
//if (strstr($string, $url)) { // mine version
if (strpos($string, $url) !== FALSE) { // Yoshi version
echo "Match found";
return true;
}
}
echo "Not found!";
return false;
Use stristr() or stripos() if you want to check case-insensitive.
This was a lot easier to do if all you want to do is find a string in an array.
$array = ["they has mystring in it", "some", "other", "elements"];
if (stripos(json_encode($array),'mystring') !== false) {
echo "found mystring";
}
Try this:
$owned_urls= array('website1.com', 'website2.com', 'website3.com');
$string = 'my domain name is website3.com';
$url_string = end(explode(' ', $string));
if (in_array($url_string,$owned_urls)){
echo "Match found";
return true;
} else {
echo "Match not found";
return false;
}
-
Thanks
Simple str_replace with count parameter would work here:
$count = 0;
str_replace($owned_urls, '', $string, $count);
// if replace is successful means the array value is present(Match Found).
if ($count > 0) {
echo "One of Array value is present in the string.";
}
More Info - https://www.techpurohit.in/extended-behaviour-explode-and-strreplace-php
I think that a faster way is to use preg_match.
$user_input = 'Something website2.com or other';
$owned_urls_array = array('website1.com', 'website2.com', 'website3.com');
if ( preg_match('('.implode('|',$owned_urls_array).')', $user_input)){
echo "Match found";
}else{
echo "Match not found";
}
$string = 'my domain name is website3.com';
$a = array('website1.com','website2.com','website3.com');
$result = count(array_filter($a, create_function('$e','return strstr("'.$string.'", $e);')))>0;
var_dump($result );
output
bool(true)
Here is a mini-function that search all values from an array in a given string.
I use this in my site to check for visitor IP is in my permitted list on certain pages.
function array_in_string($str, array $arr) {
foreach($arr as $arr_value) { //start looping the array
if (stripos($str,$arr_value) !== false) return true; //if $arr_value is found in $str return true
}
return false; //else return false
}
how to use
$owned_urls = array('website1.com', 'website2.com', 'website3.com');
//this example should return FOUND
$string = 'my domain name is website3.com';
if (array_in_string($string, $owned_urls)) {
echo "first: Match found<br>";
}
else {
echo "first: Match not found<br>";
}
//this example should return NOT FOUND
$string = 'my domain name is website4.com';
if (array_in_string($string, $owned_urls)) {
echo "second: Match found<br>";
}
else {
echo "second: Match not found<br>";
}
DEMO: http://phpfiddle.org/lite/code/qf7j-8m09
stripos function is not very strict. it's not case sensitive or it can match a part of a word
http://php.net/manual/ro/function.stripos.php
if you want that search to be case sensitive use strpos
http://php.net/manual/ro/function.strpos.php
for exact match use regex (preg_match), check this guy answer https://stackoverflow.com/a/25633879/4481831
You can concatenate the array values with implode and a separator of |
and then use preg_match to search for the value.
Here is the solution I came up with ...
$emails = array('#gmail', '#hotmail', '#outlook', '#live', '#msn', '#yahoo', '#ymail', '#aol');
$emails = implode('|', $emails);
if(!preg_match("/$emails/i", $email)){
// do something
}
If your $string is always consistent (ie. the domain name is always at the end of the string), you can use explode() with end(), and then use in_array() to check for a match (as pointed out by #Anand Solanki in their answer).
If not, you'd be better off using a regular expression to extract the domain from the string, and then use in_array() to check for a match.
$string = 'There is a url mysite3.com in this string';
preg_match('/(?:http:\/\/)?(?:www.)?([a-z0-9-_]+\.[a-z0-9.]{2,5})/i', $string, $matches);
if (empty($matches[1])) {
// no domain name was found in $string
} else {
if (in_array($matches[1], $owned_urls)) {
// exact match found
} else {
// exact match not found
}
}
The expression above could probably be improved (I'm not particularly knowledgeable in this area)
Here's a demo
You are checking whole string to the array values. So output is always false.
I use both array_filter and strpos in this case.
<?php
$urls= array('website1.com', 'website2.com', 'website3.com');
$string = 'my domain name is website3.com';
$check = array_filter($urls, function($url){
global $string;
if(strpos($string, $url))
return true;
});
echo $check?"found":"not found";
$owned_urls= array('website1.com', 'website2.com', 'website3.com');
$string = 'my domain name is website3.com';
for($i=0; $i < count($owned_urls); $i++)
{
if(strpos($string,$owned_urls[$i]) != false)
echo 'Found';
}
$message = "This is test message that contain filter world test3";
$filterWords = array('test1', 'test2', 'test3');
$messageAfterFilter = str_replace($filterWords, '',$message);
if( strlen($messageAfterFilter) != strlen($message) )
echo 'message is filtered';
else
echo 'not filtered';
I find this fast and simple without running loop.
$array = array("this", "that", "there", "here", "where");
$string = "Here comes my string";
$string2 = "I like to Move it! Move it";
$newStr = str_replace($array, "", $string);
if(strcmp($string, $newStr) == 0) {
echo 'No Word Exists - Nothing got replaced in $newStr';
} else {
echo 'Word Exists - Some Word from array got replaced!';
}
$newStr = str_replace($array, "", $string2);
if(strcmp($string2, $newStr) == 0) {
echo 'No Word Exists - Nothing got replaced in $newStr';
} else {
echo 'Word Exists - Some Word from array got replaced!';
}
Little explanation!
Create new variable with $newStr replacing value in array of original string.
Do string comparison - If value is 0, that means, strings are equal and nothing was replaced, hence no value in array exists in string.
if it is vice versa of 2, i.e, while doing string comparison, both original and new string was not matched, that means, something got replaced, hence value in array exists in string.
$search = "web"
$owned_urls = array('website1.com', 'website2.com', 'website3.com');
foreach ($owned_urls as $key => $value) {
if (stristr($value, $search) == '') {
//not fount
}else{
//found
}
this is the best approach search for any substring , case-insensitive and fast
just like like im mysql
ex:
select * from table where name = "%web%"
I came up with this function which works for me, hope this will help somebody
$word_list = 'word1, word2, word3, word4';
$str = 'This string contains word1 in it';
function checkStringAgainstList($str, $word_list)
{
$word_list = explode(', ', $word_list);
$str = explode(' ', $str);
foreach ($str as $word):
if (in_array(strtolower($word), $word_list)) {
return TRUE;
}
endforeach;
return false;
}
Also, note that answers with strpos() will return true if the matching word is a part of other word. For example if word list contains 'st' and if your string contains 'street', strpos() will return true

PHP - Using Stripos() to filter a String

I have read all thread about how to filter a string for certain needles and I think stripos() is what will do the job, however, the function does not return true when for example the first needle is found as if it is filtering the haystack using only the second value of my array.
Example :
$String = 'IWantToSolveThisProblem!!';
$needle = array('want', 'solve');
foreach ($needle as $value) {
$res = stripos($String, $value,0);
if($res !==false){
echo 'found';
}
else {
echo 'not found'; }}
In the example above the output will echo 'Found' because both values are present in my string.
The problem is that it is only using the last value of my array to loop. If the first value is present within the String and not the second it will return as false.
I dont want to run multiple if statements
You should do:
if(stripos($value,$array[0]) !== false){ //check for the first element
echo "found want";
}
if(stripos($value,$array[1]) !== false){ //check for the second element
echo "found solve";
}
I tested with this code:
<?php
$str = "IWantToSolveThisProblem!";
$str2 = 'IWantAnAnswer';
$needles = array('want', 'solve');
foreach ($needles as $needle){
$res = stripos($str2, $needle, 0);
if ($res !== false){
echo "$needle found\n";
}
else {
echo "$needle not found\n";
}
}
echo "\n";
?>
and it outputs:
$php testme.php
want found
solve not found
So it seems to work for me here... you might check for typos maybe..??!
<?php
$String = 'IWantToSolveThisProblem!!';
$needle = array('want', 'solve');
foreach ($needle as $value) {
$res = stripos($String, $value,0);
if($res !==false){
echo 'found';
}
else {
echo 'not found'; }}
?>
Output:
foundfound
If you "convert" your foreach-loop to if statements it would be the same as:
if(stripos($String,$needle[0]) !== false){ //check for the first element
echo "found";
}
if(stripos($String,$needle[1]) !== false){ //check for the second element
echo "found";
}
Output:
foundfound
So the foreach - loop does several if-conditions (one for each element in the array)
$String = 'IWantToSolveThisProblem!!'; //you were missing this semicolon
$needle = array('want', 'solve'); //no spaces before the array (not needed, I just like nospaces :P)
foreach($needle as $value) {
$res = stripos($String, $value,0);
if($res !==false){
echo 'found';
}
else {
echo 'not found'; }}
This doesn't make sense now... It's not that it's only comparing the last element. It just isn't comparing the first. See this example...
$haystack = "string to be tested";
$needles = array("string","to","pineapple","tested");
foreach($needles as $needle){
if(stripos($haystack,$needle,0)){
echo "The word \"$needle\" was found in the string \"$haystack\".";
}
else{
echo "The word \"$needle\" was NOT found in the string \"$haystack\".";
}
}
Expected Output:
The word "string" was found in the string "string to be tested".
The word "to" was found in the string "string to be tested".
The word "pineapple" was NOT found in the string "string to be tested".
The word "tested" was found in the string "string to be tested".
Actual Output:
The word "string" was NOT found in the string "string to be tested".
The word "to" was found in the string "string to be tested".
The word "pineapple" was NOT found in the string "string to be tested".
The word "tested" was found in the string "string to be tested".
It all makes sense now... From the docs:
"This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function."
So, changing if(stripos($haystack,$needle,0)) to if(stripos($haystack,$needle,0) !== False) fixes the logic.
$String = 'IWantToSolveThisProblem!!';
$needle = array('want', 'solve', 42);
foreach($needle as $value) {
if(stripos($String, $value,0) !== FALSE){
echo "found \"$value\" in \"$String \"";
}
else {
echo "$value not found";
}
}
I've interpreted your question as a search to find a function that returns true when all needles are present in the given haystack, and here's a function that does just that...
/**
* Search the haystack for all of the given needles, returning true only if
* they are all present.
*
* #param string $haystack String to search
* #param array $needles Needles to look for
* #return boolean
*/
function stripos_array($haystack, array $needles)
{
foreach ($needles as $needle)
{
if (stripos($haystack, $needle) === false) return false;
}
return true;
}
// Test the function
$string = 'IWantToSolveThisProblem!!';
$search = array('want', 'solve');
$found = stripos_array($string, $search);
echo $found ? 'found' : 'not found', "\n"; // found
$search = array('want', 'cheese');
$found = stripos_array($string, $search);
echo $found ? 'found' : 'not found', "\n"; // not found
$search = array('cheese', 'problem');
$found = stripos_array($string, $search);
echo $found ? 'found' : 'not found', "\n"; // not found
It would be trivial to change this function to return true if any of the needles are found, instead of all needles.
/**
* Search the haystack for any of the given needles, returning true if any of
* them are present.
*
* #param string $haystack String to search
* #param array $needles Needles to look for
* #return boolean
*/
function stripos_array($haystack, array $needles)
{
foreach ($needles as $needle)
{
if (stripos($haystack, $needle) !== false) return true;
}
return false;
}
You are getting "not found" because when $value becomes "solve" it is not found in $String = 'IWantAnAnswer'.

php problem: strpos function not working

why is the following php code not working:
$string = "123";
$search = "123";
if(strpos($string,$search))
{
echo "found";
}else{
echo "not found";
}
as $search is in $string - shouldn't it be triggered as found?
This is mentioned in the Manual: strpos()
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
In your case the string is found at the index 0 and in php 0 == false
The solution is to just use the strict comparator
echo strpos($string,$search) === false
? "not found"
: "found";
Another one
echo is_int(strpos($string,$search))
? "found"
: "not found";
Or something ... lets say interesting :D Just for illustration. I don't recommend this one.
echo strpos('_' . $string,$search) // we just shift the string 1 to the right
? "found"
: "not found";
This is happening because the search string is being found at position 0.
Try
if(strpos($string,$search) !== FALSE)
instead of
if(strpos($string,$search))
strpos returns the first offset where $search was found - 0. 0 in turn evaluates to false. Therefore the if fails.
If $search was not found, strpos returns FALSE. First check the return value for !== FALSE, and then check the offset.
Thanks to everyone who pointed this out in the comments.
see: http://php.net/manual/en/function.strpos.php
From the manual:
This function may return Boolean
FALSE, but may also return a
non-Boolean value which evaluates to
FALSE, such as 0 or "". Please read
the section on Booleans for more
information. Use the === operator
for testing the return value of this
function.
In your example, you should use
$string = "123";
$search = "123";
if ( false !== strpos( $string, $search ) ) {
echo "found";
} else {
echo "not found";
}
strpos returns the numeric position of the string you want to search for if it finds it. So in your case, you want to be doing this instead:
$search = "123";
$string = "123";
if (strpos($string,$search)===false) { echo "not found"; }
else { echo "found"; }
basically it returns a false if it doesn't find your string
You can use this:
<?php
$string = "123";
$find = "123";
$strpos = strpos($string, $find);
if($strpos || $strpos === (int)0) {
echo "Found it!";
} else {
echo "Not Found!";
}
?>
Well documented issue explained here. strpos is simply returning '0'

how can I do a string check inside a string in php?

Does anyone know how can I do a string check inside a string?
for example:
$variable = "Pensioner (other)";
If I want to check whether $variable contain the word 'Pensioner', how can I do it in PHP? I have tried the following code in php, but it's always return me false :(
$pos = strripos($variable,"Pensioner");
if($pos) echo "found one";
else echo "not found";
In the manual, the example uses a === for comparison. The === operator also compares the type of both operands. To check for 'not equal', use !==.
Your search target 'Pensioner' is at position 0, and the function returns 0, which equal false, hence if ($pos) failed all the time. To correct that, your code should read:
$pos = strripos($variable,"Pensioner");
if($pos !== false) echo "found one";
else echo "not found";
Update:
You are using the reverse function strripos, you need to use stripos.
if (stripos($variable, "Pensioner") !== FALSE){
// found
}
else{
// not found
}
This should do:
if (strripos($variable, "Pensioner") !== FALSE){
// found
}
else{
// not found
}
The strict type comparison (!==) is important there when using strpos/stripos.
The problem with strripos and its siblings is that they return the position of the substring found. So if the substring you're searching happens to be at the start, it returns 0 which in a boolean test is false.
Use:
if ( $pos !== FALSE ) ...
$variable = 'Pensioner (other)';
$pos = strripos($variable, 'pensioner');
if ($pos !== FALSE) {
echo 'found one';
} else {
echo 'not found';
}
^ Works for me. Note that strripos() is case insensitive. If you wanted it to be a case-sensitive search, use strrpos() instead.

check in a string php

I have a string and it can contain values like this
$string = '1,2,3,4,5';
I wanna put a check that will see if the string contains 4 or 5
if it contains 4 or 5 then I want to echo success
otherwise if it contains 9 or 10 I wanna echo fail
I know there is a n in_array function but not sure how to use it
thanks
You can test for the number 4 like this:
if(in_array('4', explode(',', $string))) echo "it's in there";
or just by string searching:
if(strpos(',4,', ','.$string.',') !== false) echo "it's in there";
in_array won't help you here because you have a string, not an array. What you're looking for is the strpos() function:
http://php.net/manual/en/function.strpos.php
Note that if it doesn't find what it's looking for in your string, it'll return false on its own, so all you have to do is check whether it returns a result or not to meet your conditions.
$set = array (1,2,3...,n); //you can use range() function if the numbers going one by one or explode if you have a string
if(in_array($var,$set))
{
Echo 'IS in ARRAY!';
} else {
Echo 'fail';
}
$goodString = '1,2,3,4,5';
$badString = '1,2,3,7,8,9,10';
function checkString($str) {
$arr = explode(',', $str);
$message = 'no message';
if (
in_array(4, $arr)||
in_array(5, $arr)
) {
$message = 'success';
} else if (
in_array(9, $arr)||
in_array(10, $arr)
) {
$message = 'fail';
}
echo $message;
}
checkString($goodString); // prints success
checkString($badString); // prints fail
you can use strpos() to check for the existence of a substring inside a string, like this:
if(strpos(','.$string.',', ','.$number_to_check_for.',') !== false) {
//success, substring was found
} else {
//error, substring was not found.
}
or you could explode it into an array then use in_array():
$array = explode(',',$string);
if(in_array($number_to_check_for, $array)) {
//success substring found
} else {
//error, substring not found
}
But I would recommend the first solution, as it is cleaner and more efficient.
Check all at once :)
if(in_array(array(4,5), explode(',', $string))) echo "success";
if(in_array(array(9,10), explode(',', $string))) echo "failure";

Categories