line brek error with search system in php - php

I am developing a system that searches for words that the user types in php files, using PHP without MySQL but I am having a problem. The system works really well when there is not a line break in the file. For example, if I search for the word "good" in a file that contains the text "good morning" works fine, but if I search for "good" in a file that contains the text "goodmorning" (with a line break) it won't list the file as a result. Here is my code:
index.php
<form action="busca.php" method="get">
<input type="text" name="s"><br>
<input type="submit">
</form>
busca.php
<?php
$pesq = (isset($_GET['s'])) ? trim($_GET['s']) : '';
if (empty($pesq)) {
echo 'Type something.';
} else {
$index = "index.php";
$busca = glob("posts/content/*.php", GLOB_BRACE);
$lendo = "";
$conteudo = "";
foreach ($busca as $item) {
if ($item !== $index) {
$abrir = fopen($item, "r");
while (!feof($abrir)) {
$lendo = fgets($abrir);
$conteudo .= $lendo;
$lendo .= strip_tags($lendo);
}
if (stristr($lendo, $pesq) == true) {
$dados = str_replace(".php", "", $item);
$dados = basename($dados);
$result[] = "$dados";
unset($dados);
}
fclose($abrir);
}
}
if (isset($result) && count($result) > 0) {
$result = array_unique($result);
echo '<ul>';
foreach ($result as $link) {
echo "<li>$link</li>";
}
echo '</ul>';
} else {
echo 'No results';
}
}
?>

Your usage of stristr is incorrect.
Compare it with false like this:
if (stristr($lendo, $pesq) !== false) {
If a string is located — the function returns the substring. Which can be casted as boolean true or false, you never know. If it doesn't find it — it returns false — the only correct value you should compare it to.
Even better to use strpos for this.
My variant:
foreach ($busca as $item) {
if ($item !== $index) {
$lendo = file_get_contents($item);
$lendo = strip_tags($lendo);
if (strpos($lendo, $pesq) !== false) {
$dados = str_replace(".php", "", basename($item));
$result[] = "$dados";
}
}
}
To fix the linebreaks - try to get rid of them
Like this:
$lendo = file_get_contents($item);
$lendo = strip_tags($lendo);
$lendo = str_replace(["\r","\n"], ' ', $lendo);

Related

i have faced a problem in search for arabic work inside an array

Hi everyone i have faced a problem during my working to return a response for a api
the main problem is
$name = "تش";
$restaurants = [
"تشك تشيكن",
"بيتزا ساخنة",
"كينتاكي",
"تشيكن سبوت"
];
foreach ($restaurants as $restaurant) {
if (strpos($restaurant, $name)) {
echo "founded";
}
}
any help ?
Your first argument should be $item and then the keyword you are searching for which is $search
So your code should look like:
$item = "أهلا وسهلا بكم";
$search = "وسهلا";
if (strpos($item, $search)){
echo "founded";
}else {
echo "not founded";
}
The first argument in strpos should be the haystack, which is the string you want to search in, and the second argument is the needle, which is the string you want to search for
<?php
$item = "أهلا وسهلا بكم";
$search = "وسهلا";
// look if $search is in $item
if (strpos($item, $search)){
echo "founded";
}else {
echo "not founded";
}
https://3v4l.org/C07o8
based on this duplicate, Arabic characters are encoded using multibyte characters, so you need to use grapheme_strpos()
if (function_exists('grapheme_strpos')) {
$pos = grapheme_strpos($tweet, $keyword);
} elseif (function_exists('mb_strpos')) {
$pos = mb_strpos($tweet, $keyword);
} else {
$pos = strpos($tweet, $keyword);
}
I have found the answer finally
$name = "تش";
$restaurants = [
"تشك تشيكن",
"بيتزا ساخنة",
"كينتاكي",
"تشيكن سبوت"
];
foreach ($restaurants as $restaurant) {
if (strpos($restaurant, $name) !== false) {
echo "founded";
}
}

PHP get possible string combination of given array which match with given string

I have an array which contains bunch of strings, and I would like to find all of the possible combinations no matter how it's being sorted that match with given string/word.
$dictionary = ['flow', 'stack', 'stackover', 'over', 'code'];
input: stackoverflow
output:
#1 -> ['stack', 'over', 'flow']
#2 -> ['stackover', 'flow']
What I've tried is, I need to exclude the array's element which doesn't contain in an input string, then tried to match every single merged element with it but I'm not sure and get stuck with this. Can anyone help me to figure the way out of this? thank you in advance, here are my code so far
<?php
$dict = ['flow', 'stack', 'stackover', 'over', 'code'];
$word = 'stackoverflow';
$dictHas = [];
foreach ($dict as $w) {
if (strpos($word, $w) !== false) {
$dictHas[] = $w;
}
}
$result = [];
foreach ($dictHas as $el) {
foreach ($dictHas as $wo) {
$merge = $el . $wo;
if ($merge == $word) {
} elseif ((strpos($word, $merge) !== false) {
}
}
}
print_r($result);
For problems like this you want to use backtracking
function splitString($string, $dict)
{
$result = [];
//if the string is already empty return empty array
if (empty($string)) {
return $result;
}
foreach ($dict as $idx => $term) {
if (strpos($string, $term) === 0) {
//if the term is at the start of string
//get the rest of string
$substr = substr($string, strlen($term));
//if all of string has been processed return only current term
if (empty($substr)) {
return [[$term]];
}
//get the dictionary without used term
$subDict = $dict;
unset($subDict[$idx]);
//get results of splitting the rest of string
$sub = splitString($substr, $subDict);
//merge them with current term
if (!empty($sub)) {
foreach ($sub as $subResult) {
$result[] = array_merge([$term], $subResult);
}
}
}
}
return $result;
}
$input = "stackoverflow";
$dict = ['flow', 'stack', 'stackover', 'over', 'code'];
$output = splitString($input, $dict);

php foreach loop doesn't gives all the results?

I am trying to get specified words out of an string.
I do not know if I forgot something but it only prints the first two values? Can someone help me with that?
Thanks for the help!
$orgData["connector"] = 'some stringy thing SMA-female N-female FME-female';
if (preg_match_all('/(N-female|SMA-female|FME-female)/',$orgData["connector"], $matches)) {
foreach ($matches as $i => $match) {
if ($match[$i] == "N-female") {
$con1 = "|Connector: N-female";
}
if ($match[$i] == "SMA-female") {
$con2 = "|Connector: SMA-female";
}
if ($match[$i] == "FME-female") {
$con3 = "|Connector: FME-female";
}
print_r($con1 . $con2 . $con3);
}
}
You may use a single variable and just append the matches once found:
$orgData = 'some stringy thing SMA-female N-female FME-female';
$con = "";
if (preg_match_all('/(?:N|SMA|FME)-female/', $orgData, $matches)) {
foreach ($matches[0] as $match) {
if ($match == "N-female") {
$con .= "|Connector: N-female";
}
if ($match == "SMA-female") {
$con .= "|Connector: SMA-female";
}
if ($match == "FME-female") {
$con .= "|Connector: FME-female";
}
}
}
echo $con; // => |Connector: SMA-female|Connector: N-female|Connector: FME-female
See the PHP demo.
Note I sharnk the pattern a bit: (?:N|SMA|FME)-female matches N, SMA or FME and then -female.

PHP in_array not working true

I have a mysql_query to select * from an 'english' list database and mysql_fetch_assoc returns an array. I try to search word 'flick' (which actually exists in the database) by using in_array() if 'flick' is found, it shouldn't be shown but it is shown. I think in_array function does not find the word 'flick'. Please look at code below:
<?php
error_reporting(E_ALL);
require 'db.php';
function spellcheck($word)
{
$output = array();
$word = mysql_real_escape_string($word);
$words = mysql_query("SELECT `word` FROM `english` WHERE LEFT(`word`, 1) = '" .
substr($word, 0, 1) . "'");
while(($words_row = mysql_fetch_assoc($words)) && (in_array($word, $words_row)==false))
{
similar_text($word, $words_row['word'], $percent);
if($percent > 82)
{
$output[] = $words_row['word'];
}
}
return (empty($output)) ? false : $output;
}
if (isset($_GET['word']) && trim($_GET['word']) != null)
{
$word = $_GET['word'];
$spellcheck = spellcheck($word);
if ($spellcheck !== false)
{
echo '<pre>' . print_r($spellcheck, true) . '</pre>';
} else {
echo '<p>' . $word . ' spelled correctly, or no suggestions founds.</p>';
}
}
?>
<form action="" method="GET">
Check single word spelling:
<input type="text" name="word" />
<input type="submit" value="Check" />
</form>
The code returns:
Array (
[0] => flick
[1] => flicks
)
But it should be:
"spelled correctly, or no suggestions founds."
replace this line
while(($words_row = mysql_fetch_assoc($words)) && (in_array($word, $words_row)==false))
with
while(($words_row = mysql_fetch_assoc($words))) {
if((in_array($word, $words_row)==false)) {
and at bottom close if statement
After 2 days working on my problem I found the answer.
the mistake is in the output of the query by mysql_fetch_assoc. Actually it returns an associative array but every key is added a space (' ') after that.
So, the result is not like abcdefg. The result is like a b c d e f g. It means when I search a special word in the associative array, the in_array() function returns false. Because for example the word 'flick' is not equal to 'flick ' and there is a space after the keys in array. I used trim() function and solved my problem:
while ($rows = mysql_fetch_assoc($query))
{
foreach($rows as $key)
{
$key = trim($key);
$array[] = $key;
}
}
if (in_array($word, $array))
{
echo "The word is spelled correctly";
} else {
foreach($array as $key)
{
similar_text($word, $key, $percent);
if ($percent > 82)
{
$output[] = $key;
}
}
}
tank you for your paying attention to my answer.

How to parse a .plist file with php?

Can i parse a plist file with php and kind of get it into an array, like the $_POST[''] so i could call $_POST['body'] and get the string that has the <key> body ?
CFPropertyList - A PHP Implementation Of Apple's plist (PropertyList)
Googling for "php plist parser" turned up this blog post that seems to be able to do what you are asking for.
Took a look at some of the libraries out there but they have external requirements and seem overkill. Here's a function that simply puts the data in to associative arrays. This worked on a couple of exported itunes plist files I tried.
// pass in the full plist file contents
function parse_plist($plist) {
$result = false;
$depth = [];
$key = false;
$lines = explode("\n", $plist);
foreach ($lines as $line) {
$line = trim($line);
if ($line) {
if ($line == '<dict>') {
if ($result) {
if ($key) {
// adding a new dictionary, the line above this one should've had the key
$depth[count($depth) - 1][$key] = [];
$depth[] =& $depth[count($depth) - 1][$key];
$key = false;
} else {
// adding a dictionary to an array
$depth[] = [];
}
} else {
// starting the first dictionary which doesn't have a key
$result = [];
$depth[] =& $result;
}
} else if ($line == '</dict>' || $line == '</array>') {
array_pop($depth);
} else if ($line == '<array>') {
$depth[] = [];
} else if (preg_match('/^\<key\>(.+)\<\/key\>\<.+\>(.+)\<\/.+\>$/', $line, $matches)) {
// <key>Major Version</key><integer>1</integer>
$depth[count($depth) - 1][$matches[1]] = $matches[2];
} else if (preg_match('/^\<key\>(.+)\<\/key\>\<(true|false)\/\>$/', $line, $matches)) {
// <key>Show Content Ratings</key><true/>
$depth[count($depth) - 1][$matches[1]] = ($matches[2] == 'true' ? 1 : 0);
} else if (preg_match('/^\<key\>(.+)\<\/key\>$/', $line, $matches)) {
// <key>1917</key>
$key = $matches[1];
}
}
}
return $result;
}

Categories