How to Display Element of Array that has specific value/character? - php

I Have A json Array from hxxp://best1st.info/Moviedb/json.php?m=tt2015381&o=json
Here is sample of the array output :
. and so on
.
.
[STORYLINE] => On planet Earth in 1988, young Peter Quill ( ) sits in the waiting room of a hospital...
[ALSO_KNOWN_AS] => Array
(
[0] => Guardianes de la galaxia = Argentina
[1] => Qalaktikanin Mühafizeçileri = Azerbaijan
[2] => Пазителите на Галактиката = Bulgaria (Bulgarian title)
[3] => Guardiões da Galáxia = Brazil
)
[RELEASE_DATES] => Array
(
.
.
. and so on
I want to check if in "ALSO_KNOWN_AS" Element, have "Argentina" word , If "ALSO_KNOWN_AS" Element have the "Argentina" word, then display it (the value).
I have try to do it (search with google and here on stackoverflow), but seem my code dont work, Can some one here help me to fix it , here is my code
$url = 'http://best1st.info/Moviedb/json.php?m=tt2015381&o=json';
$newdata = json_decode(file_get_contents($url));
$alsoKnownAs = $newdata->ALSO_KNOWN_AS;
if (in_array('Argentina', $alsoKnownAs)) {
echo "Match found";
// echo the-array-value
}
else
{
echo "Match not found";
return false;
}
Thanks You

try this
$url = 'http://best1st.info/Moviedb/json.php?m=tt2015381&o=json';
$newdata = json_decode(file_get_contents($url));
$found = false;
foreach($newdata->ALSO_KNOWN_AS as $value)
{
if(strpos($value, "Argentina") !==false)
{
echo $value;
echo "<br/>";
$found = true;
}
}
if($found===false)
{
echo "Not found";
}

function searchArray($search, $array)
{
foreach($array as $key => $value)
{
if (stristr($value, $search))
{
return true;
}
}
return false;
}
Here in the above function first argument is the string you like to search and second argument is the array and it will iterate through entire array with the function stristr whose work is to return portion on found else false.
Note: if you need case sensitive search instead of stristr use strstr or strchr
if (searchArray('Argentina', $alsoKnownAs)) {
echo "Match found";
// echo the-array-value
}
else
{
echo "Match not found";
return false;
}

Your entries in the ALSO_KNOWN_AS array are not single words like "Argentina" but rather comparisons with country names and other text. This is why in_array() won't find it. in_array() needs precise matches. So you have to check all items.
I suggest you replace the if statement by a foreach loop:
...
...
$found = false;
foreach ($alsoKnownAs as $item) {
if (strpos($item, 'Argentina') !== false) {
$found = true;
break;
}
}
if (!$found) {
echo "Match not found";
return false;
}
Hope this helps :-)

Related

How to get the values only if all the keys have matched?

I want to make a method that returns keys and values. But only if the keys include the following string "_1" and "__last".
If only one matches then exit the function, only if the two string are included in the key, return the key with the value for a weather.
$infoList = array("_key_1"=>array("time"=>9, "day"=>"Tuesday", "weather"=>"sunny",
"humidity"=>"80%"),
"_key_2"=>array("time"=>5, "day"=>"Tuesday", "weather"=>"cloudy"),
"_key__last"=>array("time"=>3, "day"=>"Sunday", "weather"=>"rainy"))
public function getData() {
$list = array();
foreach($infoList as $key){
if(preg_match('/(_key)_(_1)/', $key) && preg_match('/(_key)_(__last)/', $key) == TRUE){
$list[$key] = $list[$key]["weather"]
}
}
return $list
}
You are making your life so much more difficult that it need be, use str_contains() its easier than building complex REGEX's and getting very confused by the look of it :)
I also fixed a number of other mistakes, such as the foreach that was not going to work, so check all the code.
It is also better to pass data to a function/method otherwise you get into scoping issues!
$infoList = array("_key_1"=>array("time"=>9, "day"=>"Tuesday", "weather"=>"sunny", "humidity"=>"80%"),
"_key_2"=>array("time"=>5, "day"=>"Tuesday", "weather"=>"cloudy"),
"_key__last"=>array("time"=>3, "day"=>"Sunday", "weather"=>"rainy"));
function getData(Array $infoList) {
$list = [];
$found = 0;
foreach($infoList as $key => $val) {
if( str_contains($key, '_1') || str_contains($key, '__last') ) {
$list[$key] = $val["weather"];
$found++;
}
}
if ( $found >= 2 ) {
return $list;
} else {
return false;
}
}
$res = getData($infoList);
if ( $res !== false ){
print_r($res);
} else {
echo 'Not Found';
}
RESULTS
Array
(
[_key_1] => sunny
[_key__last] => rainy
)
If you want to stick with RegEx, you can use positive lookaheads, the same way you check for passwords characters :
<?php
$pattern = '/^(?=.*_1)(?=.*_last).*$/';
$shouldMatch = [
'_1_last',
'foo_1bar_lasthello',
'_last_1',
'foo_lastbar_1hello'
];
echo 'next ones should match : ' . PHP_EOL;
foreach ($shouldMatch as $item)
{
if (preg_match($pattern, $item))
echo $item . PHP_EOL;
}
$shouldNOTMatch = [
'_2_first',
'bar_lasthello',
'foo_las_1hello'
];
echo 'next ones should NOT match : ' . PHP_EOL;
foreach ($shouldNOTMatch as $item)
{
// v------------ check
if (!preg_match($pattern, $item))
echo $item . PHP_EOL;
}
Output :
next ones should match :
_1_last
foo_1bar_lasthello
_last_1
foo_lastbar_1hello
next ones should NOT match :
_2_first
bar_lasthello
foo_las_1hello

Search specific value in array and return value

$meal_type= "Free Breakfast|Free Wireless";
if ($meal_type != '' && $meal_type !='None') {
$meal = explode('|', $meal_type);
$meal = array_search('Breakfast',$meal);
$meal = $meal_type;
} else {
$meal= 'No Breakfast';
}
echo $meal;
This is my code. here i want to search Breakfast in the array and return searched value, if not found return No Breakfast.
Here i was explode string to array with | symbol and returned array search Breakfast if exist return funded array value else echo No Breakfast value.
A simple foreach() will do the job:-
<?php
$match_counter =0;
$array = Array
(
0 => 'Free Breakfast',
1 => 'Free Wireless Internet'
);
$search = 'Breakfast';
foreach($array as $arr){
if(stripos($arr,$search) !==false){
echo $arr.PHP_EOL;
$match_counter++;
}
}
if($match_counter ==0){
echo 'No '.$search;
}
Output:-
https://3v4l.org/ogOEB (occurrence found)
https://3v4l.org/AOuTJ (occurrence not found)
https://3v4l.org/NTH1W (occurrence found more than one time)
Reference:- stripos()
<?php
$array = array('Free Breakfast','Free Wireless Internet');
$string = 'Breakfast';
foreach ($array as $a) {
if (stripos($a, $string) !== FALSE) {
echo $string;
return true;
}
}
echo "No" .$string;
return false;
?>
You can also use stripos() for case-insensitive.
case 1 : if array contains multiple same values
<?php
$array = array('Free Breakfast','Free Wireless Internet' ,'breakfast time');
$string = 'Breakfast';
$flag=true;
foreach ($array as $key=> $a) {
if (stripos($a, $string) !== FALSE) {
$flag = false;
echo $string." contain in key position ".$key.'<br>';
//return true;
}
}
if($flag)
{
echo "No" .$string;
}
?>

How to check if a string inside of an array,contains a part of a string in php?

I have this code:
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
if(in_array("backup", $arr)){
echo "Da";
} else { echo "Nu";
}
But is not working because,in_array instruction check the array for the complete string "backup" , which doesnt exist.I need to check for a part of the string,for example,to return true because backup is a part of the "Hello_backup" and "Beautiful_backup" strings
EDIT: I take the advice and i have used stripos like this:
$arr = array("Hello_backup-2014","World!","Beautiful_backup-2014","Day!");
$word='backup';
if(stripos($arr,$word) !== false){
echo "Da";
} else { echo "Nu";}
but now i get an error: "stripos() expects parameter 1 to be string, array given in if(stripos($arr,$word) !== false){"
Use implode to basically concatenate the array values as a string, then use strpos to check for a string within a string.
The first argument you pass to implode is used to separate each value in the array.
$array = array("Hello_backup","World!","Beautiful_backup","Day!");
$r = implode(" ", $array);
if (strpos($r, "backup") !== false) {
echo "found";
}
In this case you need to use stripos(). Example:
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
$needle = 'backup';
function check($haystack, $needle) {
foreach($haystack as $word) {
if(stripos($word, $needle) !== false) {
return 'Da!'; // if found
}
}
return 'Nu'; // if not found
}
var_dump(check($arr, $needle));
Without a function:
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
$found = false;
foreach($arr as $word) {
if(stripos($word, 'backup') !== false) {
$found = true;
break;
}
}
if($found) {
echo 'Da!';
} else {
echo 'Nu';
}
Try with strpos()
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
foreach($arr as $v){
echo (strpos($v,"backup")!== false ? "Da" : "Nu");
}
output :- DaNuDaNu
Here is the one line solution for you.
$arr = array("Hello_backup-2014","World!","Beautiful_backup-2014","Day!");
$returned_a = array_map(function($u){ if(stripos($u,'backup') !== false) return "Da"; else return "Nu";}, $arr);
You can use $returned_a with array as your answer..
Array ( [0] => Da [1] => Nu [2] => Da [3] => Nu )
Use this method. It is little bit simple to use.
$matches = preg_grep('/backup/', $arr);
$keys = array_keys($matches);
print_r($matches);
Look this working example
According to your question
$matches = preg_grep('/backup/', $arr);
$keys = array_keys($matches);
$matches = trim($matches);
if($matches != '')
{echo "Da";
}else { echo "Nu";}
<?php
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
foreach($arr as $arr1) {
if (strpos ($arr1,"backup")) {
echo "Da";
} else {
echo "Nu";
}
}
?>

PHP - How i can find a partial word in array?

I have a word:
$word = "samsung";
I have array:
$myarray = Array(
[0] => "Samsung=tv"
[1] => "Apple=mobile"
[2] => "Nokia=mobile"
[3] => "LG=tv"
I need now something like this to find a partial match:
if($word in $myarray){ echo "YES"; } // samsung found in Samsung=tv
Thank you for help.
You want in_array http://us3.php.net/manual/en/function.in-array.php.
if(in_array($word,$myarray){ echo 'yes'; }
Are you looking for something like this?
<?php
$myarray = array("Samsung=tv", "Apple=mobile", "Nokia=mobile", "LG=tv");
function findSimilarWordInArray($word, $array) {
if (empty($array) && !is_array($array) return false;
foreach ($array as $key=>$value) {
if (strpos( strtolower($value), strtolower($word)) !== false) {
return true;
} // if
} // foreach
}
// use case
if ( findSimilarWordInArray('samsung',$myarray) ) {
echo "I've found it!";
}
?>
It allows you to look for a similar word in array values.
If you are looking for partial matches, you can use strpos() with a foreach loop to iterate through the array.
foreach ($myarray as $key => $value) {
if (strpos($value, $word) !== FALSE) {
echo "Yes";
}
}
There is no built in function to do a partial match, but you can easily create your own:
function in_array_partial($needle, $haystack){
$result = false;
$needle = strtolower($needle);
foreach($haystack as $elem){
if(strpos(strtolower($elem), $needle) !== false){
$result = true;
break;
}
}
return $result;
}
Usage:
if(in_array_partial('samsung', $myarray)){
echo 'yes';
}
You can try something like this:
function my_in_array($word, $array){
forach($array as $value){
if(strpos($word, $value) !== false){
return true;
}
}
return false;
}

How to search text using php if ($text contains "World")

How to search text using php?
Something like:
<?php
$text = "Hello World!";
if ($text contains "World") {
echo "True";
}
?>
Except replacing if ($text contains "World") { with a working condition.
In your case you can just use strpos(), or stripos() for case insensitive search:
if (stripos($text, "world") !== false) {
echo "True";
}
What you need is strstr()(or stristr(), like LucaB pointed out). Use it like this:
if(strstr($text, "world")) {/* do stuff */}
If you are looking an algorithm to rank search results based on relevance of multiple words here comes a quick and easy way of generating search results with PHP only.
Implementation of the vector space model in PHP
function get_corpus_index($corpus = array(), $separator=' ') {
$dictionary = array();
$doc_count = array();
foreach($corpus as $doc_id => $doc) {
$terms = explode($separator, $doc);
$doc_count[$doc_id] = count($terms);
// tf–idf, short for term frequency–inverse document frequency,
// according to wikipedia is a numerical statistic that is intended to reflect
// how important a word is to a document in a corpus
foreach($terms as $term) {
if(!isset($dictionary[$term])) {
$dictionary[$term] = array('document_frequency' => 0, 'postings' => array());
}
if(!isset($dictionary[$term]['postings'][$doc_id])) {
$dictionary[$term]['document_frequency']++;
$dictionary[$term]['postings'][$doc_id] = array('term_frequency' => 0);
}
$dictionary[$term]['postings'][$doc_id]['term_frequency']++;
}
//from http://phpir.com/simple-search-the-vector-space-model/
}
return array('doc_count' => $doc_count, 'dictionary' => $dictionary);
}
function get_similar_documents($query='', $corpus=array(), $separator=' '){
$similar_documents=array();
if($query!=''&&!empty($corpus)){
$words=explode($separator,$query);
$corpus=get_corpus_index($corpus);
$doc_count=count($corpus['doc_count']);
foreach($words as $word) {
$entry = $corpus['dictionary'][$word];
foreach($entry['postings'] as $doc_id => $posting) {
//get term frequency–inverse document frequency
$score=$posting['term_frequency'] * log($doc_count + 1 / $entry['document_frequency'] + 1, 2);
if(isset($similar_documents[$doc_id])){
$similar_documents[$doc_id]+=$score;
}
else{
$similar_documents[$doc_id]=$score;
}
}
}
// length normalise
foreach($similar_documents as $doc_id => $score) {
$similar_documents[$doc_id] = $score/$corpus['doc_count'][$doc_id];
}
// sort fro high to low
arsort($similar_documents);
}
return $similar_documents;
}
IN YOUR CASE
$query = 'world';
$corpus = array(
1 => 'hello world',
);
$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
print_r($match_results);
echo '</pre>';
RESULTS
Array
(
[1] => 0.79248125036058
)
MATCHING MULTIPLE WORDS AGAINST MULTIPLE PHRASES
$query = 'hello world';
$corpus = array(
1 => 'hello world how are you today?',
2 => 'how do you do world',
3 => 'hello, here you are! how are you? Are we done yet?'
);
$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
print_r($match_results);
echo '</pre>';
RESULTS
Array
(
[1] => 0.74864218272161
[2] => 0.43398500028846
)
from How do I check if a string contains a specific word in PHP?
This might be what you are looking for:
<?php
$text = 'This is a Simple text.';
// this echoes "is is a Simple text." because 'i' is matched first
echo strpbrk($text, 'mi');
// this echoes "Simple text." because chars are case sensitive
echo strpbrk($text, 'S');
?>
Is it?
Or maybe this:
<?php
$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";
}
?>
Or even this
<?php
$email = 'name#example.com';
$domain = strstr($email, '#');
echo $domain; // prints #example.com
$user = strstr($email, '#', true); // As of PHP 5.3.0
echo $user; // prints name
?>
You can read all about them in the documentation here:
http://php.net/manual/en/book.strings.php
in my opinion strstr() is better than strpos(). because strstr() is compatible with both PHP 4 AND PHP 5. but strpos() is only compatible with PHP 5. please note that part of servers have no PHP 5
/* https://ideone.com/saBPIe */
function search($search, $string) {
$pos = strpos($string, $search);
if ($pos === false) {
return "not found";
} else {
return "found in " . $pos;
}
}
echo search("world", "hello world");
Embed PHP online:
body, html, iframe {
width: 100% ;
height: 100% ;
overflow: hidden ;
}
<iframe src="https://ideone.com/saBPIe" ></iframe>
The best solution is my method:
In my method, only full words are detected,But in other ways it is not.
for example:
$text='hello world!';
if(strpos($text, 'wor') === FALSE) {
echo '"wor" not found in string';
}
Result: strpos returned true!!! but in my method return false.
My method:
public function searchInLine($txt,$word){
$txt=strtolower($txt);
$word=strtolower($word);
$word_length=strlen($word);
$string_length=strlen($txt);
if(strpos($txt,$word)!==false){
$indx=strpos($txt,$word);
$last_word=$indx+$word_length;
if($indx==0){
if(strpos($txt,$word." ")!==false){
return true;
}
if(strpos($txt,$word.".")!==false){
return true;
}
if(strpos($txt,$word.",")!==false){
return true;
}
if(strpos($txt,$word."?")!==false){
return true;
}
if(strpos($txt,$word."!")!==false){
return true;
}
}else if($last_word==$string_length){
if(strpos($txt," ".$word)!==false){
return true;
}
if(strpos($txt,".".$word)!==false){
return true;
}
if(strpos($txt,",".$word)!==false){
return true;
}
if(strpos($txt,"?".$word)!==false){
return true;
}
if(strpos($txt,"!".$word)!==false){
return true;
}
}else{
if(strpos($txt," ".$word." ")!==false){
return true;
}
if(strpos($txt," ".$word.".")!==false){
return true;
}
if(strpos($txt," ".$word.",")!==false){
return true;
}
if(strpos($txt," ".$word."!")!==false){
return true;
}
if(strpos($txt," ".$word."?")!==false){
return true;
}
}
}
return false;
}

Categories