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;
}
Related
How can I search a word in a PHP array?
I try in_array, but it find just exactly the same values.
<?php
$namesArray = array('Peter', 'Joe', 'Glenn', 'Cleveland');
if (in_array('Peter Parker', $namesArray)) {echo "There is.";}
else {echo "There is not.";}
I want this instance to return true. How can I do it? Is there any function?
Snippet: https://glot.io/snippets/ek086tekl0
I have to say I like the simplicity of Gre_gor's answer, but for a more dynamic method you can also use array_filter():
function my_array_search($array, $needle){
$matches = array_filter($array, function ($haystack) use ($needle){
// return stripos($needle, $haystack) !== false; make the function case insensitive
return strpos($needle, $haystack) !== false;
});
return empty($matches) ? false : $matches;
}
$namesArray = ['Peter', 'Glenn', 'Meg', 'Griffin'];
Examples:
if(my_array_search($namesArray, 'Glenn Quagmire')){
echo 'There is'; // Glenn
} else {
echo 'There is not';
}
// optionally:
if(($retval = my_array_search($namesArray, 'Peter Griffin'))){
echo 'There is';
print_r($retval); // Peter, Griffin.
} else {
echo 'There is not';
}
Now $retval is optional, it captures an array of matching subjects. This works because if the $matches variable in my_array_search is empty, it returns false instead of an empty array.
Explode your string and then check, if there are any same strings in both arrays.
$namesArray = array('Peter', 'Joe', 'Glenn', 'Cleveland');
if (array_intersect(explode(' ', 'Peter Parker'), $namesArray))
echo "There is.";
else
echo "There is not.";
You can use Regular Expressions - preg_match ('i' means case insensitive) to check if array contains some words
for example:
$namesArray = array('Peter One', 'Other Peter', 'Glenn', 'Cleveland');
$check = false;
foreach($namesArray as $name)
{
if (preg_match("/.*peter.*/i", $name)) {
$check = true;
break;
}
}
if($check)
{
echo "There is.";
}
else {
echo "There is not.";
}
So here is situation let's imagine a string and an array:
$str = 'Sample string';
$arr = array('sample', 'string')
What would be the best way to determine if the given string has all of the words contained in the array? String can be longer, and has additional words, it does not matter. The only thing I need, is a function that given a string and an array would return true, if string contains every single word that is in array (case and order I'm which they appear does not matter)
You can simply use str_word_count with extra parameter 1 like as
$str = 'Sample string';
$arr = array('sample', 'string');
$new_arr = array_intersect(array_map('strtolower',str_word_count($str,1)),$arr);
print_r($new_arr);
Output:
Array
(
[0] => sample
[1] => string
)
Demo
Try this one:
<?php
$words = array('sample', 'string');
$str = 'sample string';
strtolower($str);
$strArr = explode(' ',$str);
$wordfound = false;
foreach ($strArr as $k => $v) {
if (in_array($v,$words)) {$wordfound = true; break;}
foreach($words as $kb => $vb) {
if (strstr($v, $kb)) $wordfound = true;
break;
}
}
if ($wordfound) {
echo 'Found!';
}
else echo 'Not found!';
If performance matters, I would use an associative array:
$words = array_flip(preg_split('/\\s+/', strtolower($str)));
$result = true;
foreach ($arr as $find) {
if (!isset($words[$find])) {
$result = false;
break;
}
}
Demo
Try this out.
$strArray = explode(" ", $str);
$result = array_intersect($strArray, $arr);
if(sizeof($result) == sizeof($arr)){
return TRUE;
}else{
return FALSE;
}
if this don't work, then try swapping the inputs in array_intersect($arr, $strArray)
You can add other functions to make all lowercase before comparing to give it a finishing touch.
$str = 'Sample string';
$str1=strtolower($str);
$arr = array(
'sample',
'string'
);
foreach($arr as $val)
{
if(strpos($str1,strtolower($val)) !== false)
{
$msg='true';
}
else
{
$msg='false';
break;
}
}
echo $msg;
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";
}
}
?>
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 :-)
This question already has answers here:
String contains any items in an array (case insensitive)
(15 answers)
Closed 2 years ago.
This is for a chat page. I have a $string = "This dude is a mothertrucker". I have an array of badwords: $bads = array('truck', 'shot', etc). How could I check to see if $string contains any of the words in $bad?
So far I have:
foreach ($bads as $bad) {
if (strpos($string,$bad) !== false) {
//say NO!
}
else {
// YES! }
}
Except when I do this, when a user types in a word in the $bads list, the output is NO! followed by YES! so for some reason the code is running it twice through.
function contains($str, array $arr)
{
foreach($arr as $a) {
if (stripos($str,$a) !== false) return true;
}
return false;
}
1) The simplest way:
if ( in_array( 'three', ['one', 'three', 'seven'] ))
...
2) Another way (while checking arrays towards another arrays):
$keywords=array('one','two','three');
$targets=array('eleven','six','two');
foreach ( $targets as $string )
{
foreach ( $keywords as $keyword )
{
if ( strpos( $string, $keyword ) !== FALSE )
{ echo "The word appeared !!" }
}
}
can you please try this instead of your code
$string = "This dude is a mothertrucker";
$bads = array('truck', 'shot');
foreach($bads as $bad) {
$place = strpos($string, $bad);
if (!empty($place)) {
echo 'Bad word';
exit;
} else {
echo "Good";
}
}
There is a very short php script that you can use to identify bad words in a string which uses str_ireplace as follows:
$string = "This dude is a mean mothertrucker";
$badwords = array('truck', 'shot', 'ass');
$banstring = ($string != str_ireplace($badwords,"XX",$string))? true: false;
if ($banstring) {
echo 'Bad words found';
} else {
echo 'No bad words in the string';
}
The single line:
$banstring = ($string != str_ireplace($badwords,"XX",$string))? true: false;
does all the work.
You can flip your bad word array and do the same checking much faster. Define each bad word as a key of the array. For example,
//define global variable that is available to too part of php script
//you don't want to redefine the array each time you call the function
//as a work around you may write a class if you don't want global variable
$GLOBALS['bad_words']= array('truck' => true, 'shot' => true);
function containsBadWord($str){
//get rid of extra white spaces at the end and beginning of the string
$str= trim($str);
//replace multiple white spaces next to each other with single space.
//So we don't have problem when we use explode on the string(we dont want empty elements in the array)
$str= preg_replace('/\s+/', ' ', $str);
$word_list= explode(" ", $str);
foreach($word_list as $word){
if( isset($GLOBALS['bad_words'][$word]) ){
return true;
}
}
return false;
}
$string = "This dude is a mothertrucker";
if ( !containsBadWord($string) ){
//doesn't contain bad word
}
else{
//contains bad word
}
In this code we are just checking if an index exist rather than comparing bad word with all the words in the bad word list.
isset is much faster than in_array and marginally faster than array_key_exists.
Make sure none of the values in bad word array are set to null.
isset will return false if the array index is set to null.
Put and exit or die once it find any bad words, like this
foreach ($bads as $bad) {
if (strpos($string,$bad) !== false) {
//say NO!
}
else {
echo YES;
die(); or exit;
}
}
You can do the filter this way also
$string = "This dude is a mothertrucker";
if (preg_match_all('#\b(truck|shot|etc)\b#', $string )) //add all bad words here.
{
echo "There is a bad word in the string";
}
else {
echo "There is no bad word in the string";
}
Wanted this?
$string = "This dude is a mothertrucker";
$bads = array('truck', 'shot', 'mothertrucker');
foreach ($bads as $bad) {
if (strstr($string,$bad) !== false) {
echo 'NO<br>';
}
else {
echo 'YES<br>';
}
}
If you want to do with array_intersect(), then use below code :
function checkString(array $arr, $str) {
$str = preg_replace( array('/[^ \w]+/', '/\s+/'), ' ', strtolower($str) ); // Remove Special Characters and extra spaces -or- convert to LowerCase
$matchedString = array_intersect( explode(' ', $str), $arr);
if ( count($matchedString) > 0 ) {
return true;
}
return false;
}
I would go that way if chat string is not that long.
$badwords = array('mothertrucker', 'ash', 'whole');
$chatstr = 'This dude is a mothertrucker';
$chatstrArr = explode(' ',$chatstr);
$badwordfound = false;
foreach ($chatstrArr as $k => $v) {
if (in_array($v,$badwords)) {$badwordfound = true; break;}
foreach($badwords as $kb => $vb) {
if (strstr($v, $kb)) $badwordfound = true;
break;
}
}
if ($badwordfound) { echo 'You\'re nasty!';}
else echo 'GoodGuy!';
$string = "This dude is a good man";
$bad = array('truck','shot','etc');
$flag='0';
foreach($bad as $word){
if(in_array($word,$string))
{
$flag=1;
}
}
if($flag==1)
echo "Exist";
else
echo "Not Exist";