Answer the question
In order to leave comments, you need to log in
PHP. word search?
Good day.
The problem is this, there is an array of words in which I need to find words with a specific beginning or end. This is what I implemented. Then there was a need for a third parameter - this is a search in the middle of a word, some set of letters. I also managed to do this. But I can't make the last parameter optional.
Here is a loop that iterates over an array of words.
//$viewFile - массив слов
//$starting - начало
//$ending - конец
//$middle - в центре
//$*Chars - количество символов
for ($i = $start ; $i <= $amount && $currentCount < $step; $i++) {
$str = trim($viewFile[$i]); //обрезаем пробелы
$haystack = strlen($str); //считаем количество символов в слове
if ($str != "" && strcasecmp(substr($str, 0, $startingChars), $starting) == 0 && strcasecmp(mb_substr($str, $haystack - $endingChars), $ending) == 0 && stripos($str, $middle) ) {
$currentCount++;
echo '<span class="badge">' . ($currentCount+$curr) . '</span> ';
echo $viewFile[$i];
echo '<br>';
}
}
Answer the question
In order to leave comments, you need to log in
In general, I got out of the situation like this.
for ($i = $start ; $i <= $amount && $currentCount < $step; $i++) {
$str = trim($viewFile[$i]); //обрезаем пробелы
$haystack = strlen($str); //считаем количество символов в слове
if ($middleChars != "" ){
if ($str != "" && strcasecmp(substr($str, 0, $startingChars), $starting) == 0 && strcasecmp(mb_substr($str, $haystack - $endingChars), $ending) == 0 && stripos($str, $middle) )
{
$currentCount++;
echo '<span class="badge">' . ($currentCount+$curr) . '</span> ';
echo $viewFile[$i];
echo '<br>';
}
}
else
{
if ($str != "" && strcasecmp(substr($str, 0, $startingChars), $starting) == 0 && strcasecmp(mb_substr($str, $haystack - $endingChars), $ending) == 0 )
{
$currentCount++;
echo '<span class="badge">' . ($currentCount+$curr) . '</span> ';
echo $viewFile[$i];
echo '<br>';
}
}
}
$b = $str != "" && strcasecmp(substr($str, 0, $startingChars), $starting) == 0 && strcasecmp(mb_substr($str, $haystack - $endingChars), $ending) == 0;
if ($middle != "") $b = $b && stripos($str, $middle);
Why not use regular expressions?
As I understand it, we need a function that is passed five parameters, one of which is optional. Then you can do it like this.
function my_compare($haystack, $needle, $begin, $end, $middle = false) {
// Используем "ленивую" особенность проверки условий в PHP
$begin && $regexp[] = "$needle.+";
$end && $regexp[] = ".+$needle";
$middle && $regexp[] = ".+$needle.+";
$result = array();
foreach $regexp as $pattern {
$result = array_merge($result, preg_grep($pattern, $haystack));
}
return $result;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question